diff --git "a/data/dataset_Multi_scale_modeling.csv" "b/data/dataset_Multi_scale_modeling.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Multi_scale_modeling.csv" @@ -0,0 +1,116333 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/RunLammps.py",".py","1100","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Fe_2.eam.fs' +element='Fe' +temp=300 +tempDamp=0.01 +lattice=2.855312 +minEng=-4.0814287 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/RunLammps.py",".py","1097","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Fe_2.eam.fs' +element='Fe' +temp=0 +tempDamp=0.01 +lattice=2.855312 +minEng=-4.122435 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/RunLammps.py",".py","1101","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Fe_2.eam.fs' +element='Fe' +temp=600 +tempDamp=0.01 +lattice=2.855312 +minEng=-4.03765613 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Fe/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/RunLammps.py",".py","1098","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Na.eam.fs' +element='Na' +temp=300 +tempDamp=0.01 +lattice=4.22786 +minEng=-1.06831204 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/RunLammps.py",".py","1094","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Na.eam.fs' +element='Na' +temp=0 +tempDamp=0.01 +lattice=4.22786 +minEng=-1.111022 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/RunLammps.py",".py","1099","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Na.eam.fs' +element='Na' +temp=600 +tempDamp=0.01 +lattice=4.22786 +minEng=-0.986141672 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Na/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/RunLammps.py",".py","1101","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Ni99.eam.alloy' +element='Ni' +temp=300 +tempDamp=0.01 +lattice=3.52 +minEng=-4.413147074 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/RunLammps.py",".py","1095","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Ni99.eam.alloy' +element='Ni' +temp=0 +tempDamp=0.01 +lattice=3.52 +minEng=-4.44999 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/RunLammps.py",".py","1101","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Ni99.eam.alloy' +element='Ni' +temp=600 +tempDamp=0.01 +lattice=3.52 +minEng=-4.375552545 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Ni/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/RunLammps.py",".py","1106","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Cu_mishin1.eam.alloy' +element='Cu' +temp=300 +tempDamp=0.01 +lattice=3.615 +minEng=-3.5002365 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/RunLammps.py",".py","1100","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Cu_mishin1.eam.alloy' +element='Cu' +temp=0 +tempDamp=0.01 +lattice=3.615 +minEng=-3.540 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/RunLammps.py",".py","1109","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Cu_mishin1.eam.alloy' +element='Cu' +temp=600 +tempDamp=0.01 +lattice=3.615 +minEng=-3.4586429193 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Cu/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/RunLammps.py",".py","1097","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=300 +tempDamp=0.01 +lattice=4.05 +minEng=-3.32104 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/RunLammps.py",".py","1092","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=0 +tempDamp=0.01 +lattice=4.05 +minEng=-3.36 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/WriteLammps.py",".py","5580","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -10 10 -10 10 -10 10 units lattice +create_box 2 whole +region upper block INF INF 0 10 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -10 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/RunLammps.py",".py","1099","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=600 +tempDamp=0.01 +lattice=4.05 +minEng=-3.2795945 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack101010/Experiments/Al/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/RunLammps.py",".py","1100","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Fe_2.eam.fs' +element='Fe' +temp=300 +tempDamp=0.01 +lattice=2.855312 +minEng=-4.0814287 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/RunLammps.py",".py","1097","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Fe_2.eam.fs' +element='Fe' +temp=0 +tempDamp=0.01 +lattice=2.855312 +minEng=-4.122435 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/RunLammps.py",".py","1101","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Fe_2.eam.fs' +element='Fe' +temp=600 +tempDamp=0.01 +lattice=2.855312 +minEng=-4.03765613 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Fe/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/RunLammps.py",".py","1098","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Na.eam.fs' +element='Na' +temp=300 +tempDamp=0.01 +lattice=4.22786 +minEng=-1.06831204 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/RunLammps.py",".py","1094","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Na.eam.fs' +element='Na' +temp=0 +tempDamp=0.01 +lattice=4.22786 +minEng=-1.111022 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/RunLammps.py",".py","1099","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Na.eam.fs' +element='Na' +temp=600 +tempDamp=0.01 +lattice=4.22786 +minEng=-0.986141672 +A=[1,0,0] +typeAtom='bcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Na/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/RunLammps.py",".py","1101","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Ni99.eam.alloy' +element='Ni' +temp=300 +tempDamp=0.01 +lattice=3.52 +minEng=-4.413147074 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/RunLammps.py",".py","1095","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Ni99.eam.alloy' +element='Ni' +temp=0 +tempDamp=0.01 +lattice=3.52 +minEng=-4.44999 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/RunLammps.py",".py","1101","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Ni99.eam.alloy' +element='Ni' +temp=600 +tempDamp=0.01 +lattice=3.52 +minEng=-4.375552545 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Ni/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/RunLammps.py",".py","1106","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Cu_mishin1.eam.alloy' +element='Cu' +temp=300 +tempDamp=0.01 +lattice=3.615 +minEng=-3.5002365 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/RunLammps.py",".py","1100","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Cu_mishin1.eam.alloy' +element='Cu' +temp=0 +tempDamp=0.01 +lattice=3.615 +minEng=-3.540 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/RunLammps.py",".py","1109","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Cu_mishin1.eam.alloy' +element='Cu' +temp=600 +tempDamp=0.01 +lattice=3.615 +minEng=-3.4586429193 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Cu/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/RunLammps.py",".py","1097","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=300 +tempDamp=0.01 +lattice=4.05 +minEng=-3.32104 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/300/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/WriteLammps.py",".py","5571","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 35000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/RunLammps.py",".py","1092","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=0 +tempDamp=0.01 +lattice=4.05 +minEng=-3.36 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/0/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/WriteLammps.py",".py","5572","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 100000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/RunLammps.py",".py","1099","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=600 +tempDamp=0.01 +lattice=4.05 +minEng=-3.2795945 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Experiments/Al/600/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/fractions.py",".py","22391","607","# Originally contributed by Sjoerd Mullender. +# Significantly modified by Jeffrey Yasskin . + +""""""Rational, infinite-precision, real numbers."""""" + +from __future__ import division +from decimal import Decimal +import math +import numbers +import operator +import re + +__all__ = ['Fraction', 'gcd'] + +Rational = numbers.Rational + + +def gcd(a, b): + """"""Calculate the Greatest Common Divisor of a and b. + + Unless b==0, the result will have the same sign as b (so that when + b is divided by it, the result comes out positive). + """""" + while b: + a, b = b, a%b + return a + + +_RATIONAL_FORMAT = re.compile(r"""""" + \A\s* # optional whitespace at the start, then + (?P[-+]?) # an optional sign, then + (?=\d|\.\d) # lookahead for digit or .digit + (?P\d*) # numerator (possibly empty) + (?: # followed by + (?:/(?P\d+))? # an optional denominator + | # or + (?:\.(?P\d*))? # an optional fractional part + (?:E(?P[-+]?\d+))? # and optional exponent + ) + \s*\Z # and optional whitespace to finish +"""""", re.VERBOSE | re.IGNORECASE) + + +class Fraction(Rational): + """"""This class implements rational numbers. + + In the two-argument form of the constructor, Fraction(8, 6) will + produce a rational number equivalent to 4/3. Both arguments must + be Rational. The numerator defaults to 0 and the denominator + defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. + + Fractions can also be constructed from: + + - numeric strings similar to those accepted by the + float constructor (for example, '-2.3' or '1e10') + + - strings of the form '123/456' + + - float and Decimal instances + + - other Rational instances (including integers) + + """""" + + __slots__ = ('_numerator', '_denominator') + + # We're immutable, so use __new__ not __init__ + def __new__(cls, numerator=0, denominator=None): + """"""Constructs a Fraction. + + Takes a string like '3/2' or '1.5', another Rational instance, a + numerator/denominator pair, or a float. + + Examples + -------- + + >>> Fraction(10, -8) + Fraction(-5, 4) + >>> Fraction(Fraction(1, 7), 5) + Fraction(1, 35) + >>> Fraction(Fraction(1, 7), Fraction(2, 3)) + Fraction(3, 14) + >>> Fraction('314') + Fraction(314, 1) + >>> Fraction('-35/4') + Fraction(-35, 4) + >>> Fraction('3.1415') # conversion from numeric string + Fraction(6283, 2000) + >>> Fraction('-47e-2') # string may include a decimal exponent + Fraction(-47, 100) + >>> Fraction(1.47) # direct construction from float (exact conversion) + Fraction(6620291452234629, 4503599627370496) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(Decimal('1.47')) + Fraction(147, 100) + + """""" + self = super(Fraction, cls).__new__(cls) + + if denominator is None: + if isinstance(numerator, Rational): + self._numerator = numerator.numerator + self._denominator = numerator.denominator + return self + + elif isinstance(numerator, float): + # Exact conversion from float + value = Fraction.from_float(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, Decimal): + value = Fraction.from_decimal(numerator) + self._numerator = value._numerator + self._denominator = value._denominator + return self + + elif isinstance(numerator, basestring): + # Handle construction from strings. + m = _RATIONAL_FORMAT.match(numerator) + if m is None: + raise ValueError('Invalid literal for Fraction: %r' % + numerator) + numerator = int(m.group('num') or '0') + denom = m.group('denom') + if denom: + denominator = int(denom) + else: + denominator = 1 + decimal = m.group('decimal') + if decimal: + scale = 10**len(decimal) + numerator = numerator * scale + int(decimal) + denominator *= scale + exp = m.group('exp') + if exp: + exp = int(exp) + if exp >= 0: + numerator *= 10**exp + else: + denominator *= 10**-exp + if m.group('sign') == '-': + numerator = -numerator + + else: + raise TypeError(""argument should be a string "" + ""or a Rational instance"") + + elif (isinstance(numerator, Rational) and + isinstance(denominator, Rational)): + numerator, denominator = ( + numerator.numerator * denominator.denominator, + denominator.numerator * numerator.denominator + ) + else: + raise TypeError(""both arguments should be "" + ""Rational instances"") + + if denominator == 0: + raise ZeroDivisionError('Fraction(%s, 0)' % numerator) + g = gcd(numerator, denominator) + self._numerator = numerator // g + self._denominator = denominator // g + return self + + @classmethod + def from_float(cls, f): + """"""Converts a finite float to a rational number, exactly. + + Beware that Fraction.from_float(0.3) != Fraction(3, 10). + + """""" + if isinstance(f, numbers.Integral): + return cls(f) + elif not isinstance(f, float): + raise TypeError(""%s.from_float() only takes floats, not %r (%s)"" % + (cls.__name__, f, type(f).__name__)) + if math.isnan(f) or math.isinf(f): + raise TypeError(""Cannot convert %r to %s."" % (f, cls.__name__)) + return cls(*f.as_integer_ratio()) + + @classmethod + def from_decimal(cls, dec): + """"""Converts a finite Decimal instance to a rational number, exactly."""""" + from decimal import Decimal + if isinstance(dec, numbers.Integral): + dec = Decimal(int(dec)) + elif not isinstance(dec, Decimal): + raise TypeError( + ""%s.from_decimal() only takes Decimals, not %r (%s)"" % + (cls.__name__, dec, type(dec).__name__)) + if not dec.is_finite(): + # Catches infinities and nans. + raise TypeError(""Cannot convert %s to %s."" % (dec, cls.__name__)) + sign, digits, exp = dec.as_tuple() + digits = int(''.join(map(str, digits))) + if sign: + digits = -digits + if exp >= 0: + return cls(digits * 10 ** exp) + else: + return cls(digits, 10 ** -exp) + + def limit_denominator(self, max_denominator=1000000): + """"""Closest Fraction to self with denominator at most max_denominator. + + >>> Fraction('3.141592653589793').limit_denominator(10) + Fraction(22, 7) + >>> Fraction('3.141592653589793').limit_denominator(100) + Fraction(311, 99) + >>> Fraction(4321, 8765).limit_denominator(10000) + Fraction(4321, 8765) + + """""" + # Algorithm notes: For any real number x, define a *best upper + # approximation* to x to be a rational number p/q such that: + # + # (1) p/q >= x, and + # (2) if p/q > r/s >= x then s > q, for any rational r/s. + # + # Define *best lower approximation* similarly. Then it can be + # proved that a rational number is a best upper or lower + # approximation to x if, and only if, it is a convergent or + # semiconvergent of the (unique shortest) continued fraction + # associated to x. + # + # To find a best rational approximation with denominator <= M, + # we find the best upper and lower approximations with + # denominator <= M and take whichever of these is closer to x. + # In the event of a tie, the bound with smaller denominator is + # chosen. If both denominators are equal (which can happen + # only when max_denominator == 1 and self is midway between + # two integers) the lower bound---i.e., the floor of self, is + # taken. + + if max_denominator < 1: + raise ValueError(""max_denominator should be at least 1"") + if self._denominator <= max_denominator: + return Fraction(self) + + p0, q0, p1, q1 = 0, 1, 1, 0 + n, d = self._numerator, self._denominator + while True: + a = n//d + q2 = q0+a*q1 + if q2 > max_denominator: + break + p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 + n, d = d, n-a*d + + k = (max_denominator-q0)//q1 + bound1 = Fraction(p0+k*p1, q0+k*q1) + bound2 = Fraction(p1, q1) + if abs(bound2 - self) <= abs(bound1-self): + return bound2 + else: + return bound1 + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + + def __repr__(self): + """"""repr(self)"""""" + return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) + + def __str__(self): + """"""str(self)"""""" + if self._denominator == 1: + return str(self._numerator) + else: + return '%s/%s' % (self._numerator, self._denominator) + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """"""Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. + + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) + + In general, we want to implement the arithmetic operations so + that mixed-mode operations either call an implementation whose + author knew about the types of both arguments, or convert both + to the nearest built in type and do the operation there. In + Fraction, that means that we define __add__ and __radd__ as: + + def __add__(self, other): + # Both types have numerators/denominator attributes, + # so do the operation directly + if isinstance(other, (int, long, Fraction)): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + # float and complex don't have those operations, but we + # know about those types, so special case them. + elif isinstance(other, float): + return float(self) + other + elif isinstance(other, complex): + return complex(self) + other + # Let the other type take over. + return NotImplemented + + def __radd__(self, other): + # radd handles more types than add because there's + # nothing left to fall back to. + if isinstance(other, Rational): + return Fraction(self.numerator * other.denominator + + other.numerator * self.denominator, + self.denominator * other.denominator) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + return NotImplemented + + + There are 5 different cases for a mixed-type addition on + Fraction. I'll refer to all of the above code that doesn't + refer to Fraction, float, or complex as ""boilerplate"". 'r' + will be an instance of Fraction, which is a subtype of + Rational (r : Fraction <: Rational), and b : B <: + Complex. The first three involve 'r + b': + + 1. If B <: Fraction, int, float, or complex, we handle + that specially, and all is well. + 2. If Fraction falls back to the boilerplate code, and it + were to return a value from __add__, we'd miss the + possibility that B defines a more intelligent __radd__, + so the boilerplate should return NotImplemented from + __add__. In particular, we don't handle Rational + here, even though we could get an exact answer, in case + the other type wants to do something special. + 3. If B <: Fraction, Python tries B.__radd__ before + Fraction.__add__. This is ok, because it was + implemented with knowledge of Fraction, so it can + handle those instances before delegating to Real or + Complex. + + The next two situations describe 'b + r'. We assume that b + didn't know about Fraction in its implementation, and that it + uses similar boilerplate code: + + 4. If B <: Rational, then __radd_ converts both to the + builtin rational type (hey look, that's us) and + proceeds. + 5. Otherwise, __radd__ tries to find the nearest common + base ABC, and fall back to its builtin type. Since this + class doesn't subclass a concrete type, there's no + implementation to fall back to, so we need to try as + hard as possible to return an actual value, or the user + will get a TypeError. + + """""" + def forward(a, b): + if isinstance(b, (int, long, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """"""a + b"""""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + def _sub(a, b): + """"""a - b"""""" + return Fraction(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) + + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """"""a * b"""""" + return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a, b): + """"""a / b"""""" + return Fraction(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) + + def __floordiv__(a, b): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __rfloordiv__(b, a): + """"""a // b"""""" + # Will be math.floor(a / b) in 3.0. + div = a / b + if isinstance(div, Rational): + # trunc(math.floor(div)) doesn't work if the rational is + # more precise than a float because the intermediate + # rounding may cross an integer boundary. + return div.numerator // div.denominator + else: + return math.floor(div) + + def __mod__(a, b): + """"""a % b"""""" + div = a // b + return a - b * div + + def __rmod__(b, a): + """"""a % b"""""" + div = a // b + return a - b * div + + def __pow__(a, b): + """"""a ** b + + If b is not an integer, the result will be a float or complex + since roots are generally irrational. If b is an integer, the + result will be rational. + + """""" + if isinstance(b, Rational): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power) + else: + return Fraction(a._denominator ** -power, + a._numerator ** -power) + else: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b + + def __rpow__(b, a): + """"""a ** b"""""" + if b._denominator == 1 and b._numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b._numerator + + if isinstance(a, Rational): + return Fraction(a.numerator, a.denominator) ** b + + if b._denominator == 1: + return a ** b._numerator + + return a ** float(b) + + def __pos__(a): + """"""+a: Coerces a subclass instance to Fraction"""""" + return Fraction(a._numerator, a._denominator) + + def __neg__(a): + """"""-a"""""" + return Fraction(-a._numerator, a._denominator) + + def __abs__(a): + """"""abs(a)"""""" + return Fraction(abs(a._numerator), a._denominator) + + def __trunc__(a): + """"""trunc(a)"""""" + if a._numerator < 0: + return -(-a._numerator // a._denominator) + else: + return a._numerator // a._denominator + + def __hash__(self): + """"""hash(self) + + Tricky because values that are exactly representable as a + float must have the same hash as that float. + + """""" + # XXX since this method is expensive, consider caching the result + if self._denominator == 1: + # Get integers right. + return hash(self._numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self._numerator, self._denominator)) + + def __eq__(a, b): + """"""a == b"""""" + if isinstance(b, Rational): + return (a._numerator == b.numerator and + a._denominator == b.denominator) + if isinstance(b, numbers.Complex) and b.imag == 0: + b = b.real + if isinstance(b, float): + if math.isnan(b) or math.isinf(b): + # comparisons with an infinity or nan should behave in + # the same way for any finite a, so treat a as zero. + return 0.0 == b + else: + return a == a.from_float(b) + else: + # Since a doesn't know how to compare with b, let's give b + # a chance to compare itself with a. + return NotImplemented + + def _richcmp(self, other, op): + """"""Helper for comparison operators, for internal use only. + + Implement comparison between a Rational instance `self`, and + either another Rational instance or a float `other`. If + `other` is not a Rational instance or a float, return + NotImplemented. `op` should be one of the six standard + comparison operators. + + """""" + # convert other to a Rational instance where reasonable. + if isinstance(other, Rational): + return op(self._numerator * other.denominator, + self._denominator * other.numerator) + # comparisons with complex should raise a TypeError, for consistency + # with int<->complex, float<->complex, and complex<->complex comparisons. + if isinstance(other, complex): + raise TypeError(""no ordering relation is defined for complex numbers"") + if isinstance(other, float): + if math.isnan(other) or math.isinf(other): + return op(0.0, other) + else: + return op(self, self.from_float(other)) + else: + return NotImplemented + + def __lt__(a, b): + """"""a < b"""""" + return a._richcmp(b, operator.lt) + + def __gt__(a, b): + """"""a > b"""""" + return a._richcmp(b, operator.gt) + + def __le__(a, b): + """"""a <= b"""""" + return a._richcmp(b, operator.le) + + def __ge__(a, b): + """"""a >= b"""""" + return a._richcmp(b, operator.ge) + + def __nonzero__(a): + """"""a != 0"""""" + return a._numerator != 0 + + # support for pickling, copy, and deepcopy + + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Fraction: + return self # I'm immutable; therefore I am my own clone + return self.__class__(self._numerator, self._denominator) + + def __deepcopy__(self, memo): + if type(self) == Fraction: + return self # My components are also immutable + return self.__class__(self._numerator, self._denominator) + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/WriteLammps.py",".py","5571","138","import shutil + +def write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom): + + x1=[int(M1[0][0]),int(M1[0][1]),int(M1[0][2])] + y1=[int(M1[1][0]),int(M1[1][1]),int(M1[1][2])] + z1=[int(M1[2][0]),int(M1[2][1]),int(M1[2][2])] + + x2=[int(M2[0][0]),int(M2[0][1]),int(M2[0][2])] + y2=[int(M2[1][0]),int(M2[1][1]),int(M2[1][2])] + z2=[int(M2[2][0]),int(M2[2][1]),int(M2[2][2])] + + shutil.copy('../../Potentials/'+str(potential),'.') + + LammpsInFile=open('GB.in','w') + + ContentComment=""""""# LAMMPS Input File for Grain Boundaries +# Mark Tschopp, Dec2009 +# This file will generate a single Sigma5(310) STGB \n"""""" + + ContentInitSim=""""""\n # ---------- Initialize Simulation --------------------- +clear +units metal +dimension 3 +boundary p p p +atom_style atomic \n"""""" + + ContentAtomStruct1=""""""\n # ---------- Create Atomistic Structure --------------------- +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" +region whole block -5 5 -5 5 -5 5 units lattice +create_box 2 whole +region upper block INF INF 0 5 INF INF units lattice + +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x1[0])+"" "" + str(x1[1]) + "" "" + str(x1[2]) +"""""" orient y """"""+ str(y1[0])+"" "" + str(y1[1]) + "" "" + str(y1[2]) +"""""" orient z """""" +str(z1[0])+"" "" + str(z1[1]) + "" "" + str(z1[2]) +""""""\n"""""" + + + ContentAtomStruct2=""""""\n create_atoms 1 region upper +region lower block INF INF -5 0.000000 INF INF units lattice +lattice """"""+str(typeAtom)+"""""" """"""+str(lattice)+"""""" orient x """""" +str(x2[0])+"" "" + str(x2[1]) + "" "" + str(x2[2]) +"""""" orient y """"""+ str(y2[0])+"" "" + str(y2[1]) + "" "" + str(y2[2]) +"""""" orient z """""" +str(z2[0])+"" "" + str(z2[1]) + "" "" + str(z2[2]) +""""""\n"""""" + + ContentAtomStruct3=""""""\n create_atoms 2 region lower +group upper type 1 +group lower type 2 +replicate 1 1 1 \n"""""" + + ContentInterPot=""""""\n # ---------- Define Interatomic Potential --------------------- +pair_style eam/alloy +pair_coeff * * """"""+str(potential)+"" ""+str(element)+ "" ""+str(element) +"""""" +neighbor 2.0 bin +neigh_modify delay 10 check yes \n"""""" + + ContentDisplace=""""""\n # ---------- Displace atoms and delete overlapping atoms --------------------- +displace_atoms upper move 0 0 0 units lattice +delete_atoms overlap 0.35 lower upper \n"""""" + + ContentSettings=""""""\n # ---------- Define Settings --------------------- +compute csym all centro/atom """"""+str(typeAtom)+"""""" +compute eng all pe/atom +compute eatoms all reduce sum c_eng + +#write_dump all custom dump.img_orig.cfg mass type xs ys zs \n"""""" + + ContentEquil=""""""\n # ----------- EQUILIBRATION -------------------- +write_dump all custom dump.img_pre_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +timestep 0.001 +velocity all create """"""+str(temp)+"""""" 12345 mom yes rot no +fix 2 all npt temp """"""+ str(temp) + "" "" + str(temp)+ "" "" + str(tempDamp)+"""""" iso 0 0 1 drag 1 + +thermo 1000 +thermo_style custom step temp pe lx ly lz press pxx pyy pzz c_eatoms +dump 5 all cfg 1000 dump.equal_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 5 element """"""+str(element)+"" ""+str(element) + """""" + +# Run for at least 10 picosecond (assuming 1 fs timestep) +#write_dump all custom dump.img_post_equil.cfg mass type xs ys zs + +run 35000 +unfix 2\n"""""" + + ContentMin1=""""""\n # ---------- Run Minimization --------------------- +write_dump all custom dump.img_post_equil_""""""+str(theta)+"""""".cfg mass type xs ys zs +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +dump 1 all cfg 25 dump.sig5_minimization_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +min_style cg +minimize 1e-15 1e-15 5000 5000 +undump 1 \n"""""" + + ContentMin2=""""""\n # ---------- Run Minimization 2--------------------- +# Now allow the box to expand/contract perpendicular to the grain boundary +reset_timestep 0 +thermo 10 +thermo_style custom step pe lx ly lz press pxx pyy pzz c_eatoms +fix 1 all box/relax y 0 vmax 0.001 +min_style cg +minimize 1e-15 1e-15 5000 5000 \n"""""" + + ContentGBEng=""""""\n # ---------- Calculate GB Energy --------------------- +variable minimumenergy equal """"""+str(minEng)+"""""" +variable esum equal ""v_minimumenergy * count(all)"" +variable xseng equal ""c_eatoms - (v_minimumenergy * count(all))"" +variable gbarea equal ""lx * lz * 2"" +variable gbe equal ""(c_eatoms - (v_minimumenergy * count(all)))/v_gbarea"" +variable gbemJm2 equal ${gbe}*16021.7733 +variable gbernd equal round(${gbemJm2}) +print ""GB energy is ${gbemJm2} mJ/m^2"" \n"""""" + + ContentDumpData=""""""\n # ---------- Dump data into Data file ------------- +reset_timestep 0 +dump 1 all cfg 1000 dump.al_sig5_310_*.cfg mass type xs ys zs c_csym c_eng fx fy fz +dump_modify 1 element """"""+str(element)+"" ""+str(element)+"""""" +minimize 1e-15 1e-15 5000 5000 +undump 1 + +write_restart restart.al_sig5_310_stgb +write_dump all custom dump.img_post_minimize_""""""+str(theta)+"""""".cfg mass type xs ys zs +print ""All done"" \n"""""" + + LammpsInFile.write(ContentComment) + LammpsInFile.write(ContentInitSim) + LammpsInFile.write(ContentAtomStruct1) + LammpsInFile.write(ContentAtomStruct2) + LammpsInFile.write(ContentAtomStruct3) + LammpsInFile.write(ContentInterPot) + LammpsInFile.write(ContentDisplace) + LammpsInFile.write(ContentSettings) + if(temp != 0): + LammpsInFile.write(ContentEquil) + LammpsInFile.write(ContentMin1) + LammpsInFile.write(ContentMin2) + LammpsInFile.write(ContentGBEng) + LammpsInFile.write(ContentDumpData) + + LammpsInFile.close() +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/Quaternion.py",".py","12278","415",""""""" +Quaternion provides a class for manipulating quaternion objects. This class provides: + + - a convenient constructor to convert to/from Euler Angles (RA,Dec,Roll) + to/from quaternions + - class methods to multiply and divide quaternions +"""""" + +__copyright__ = """""" +Copyright (c) 2009, Smithsonian Astrophysical Observatory +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the 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 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 numpy as np +from math import cos, sin, radians, degrees, atan2, sqrt + +class Quat(object): + """""" + Quaternion class + + Example usage:: + + >>> from Quaternion import Quat + >>> quat = Quat((12,45,45)) + >>> quat.ra, quat.dec, quat.roll + (12, 45, 45) + >>> quat.q + array([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697 ]) + >>> q2 = Quat([ 0.38857298, -0.3146602 , 0.23486498, 0.8335697]) + >>> q2.ra + 11.999999315925008 + + + Multiplication and division operators are overloaded for the class to + perform appropriate quaternion multiplication and division. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 * q2 + + + :param attitude: initialization attitude for quat + + ``attitude`` may be: + * another Quat + * a 4 element array (expects x,y,z,w quat form) + * a 3 element array (expects ra,dec,roll in degrees) + * a 3x3 transform/rotation matrix + + """""" + def __init__(self, attitude): + self._q = None + self._equatorial = None + self._T = None + # checks to see if we've been passed a Quat + if isinstance(attitude, Quat): + self._set_q(attitude.q) + else: + # make it an array and check to see if it is a supported shape + attitude = np.array(attitude) + if len(attitude) == 4: + self._set_q(attitude) + elif attitude.shape == (3,3): + self._set_transform(attitude) + elif attitude.shape == (3,): + self._set_equatorial(attitude) + else: + raise TypeError(""attitude is not one of possible types (3 or 4 elements, Quat, or 3x3 matrix)"") + + + def _set_q(self, q): + """""" + Set the value of the 4 element quaternion vector + + :param q: list or array of normalized quaternion elements + """""" + q = np.array(q) + if abs(np.sum(q**2) - 1.0) > 1e-6: + raise ValueError('Quaternion must be normalized so sum(q**2) == 1; use Quaternion.normalize') + self._q = (q if q[3] > 0 else -q) + # Erase internal values of other representations + self._equatorial = None + self._T = None + + def _get_q(self): + """""" + Retrieve 4-vector of quaternion elements in [x, y, z, w] form + + :rtype: numpy array + + """""" + if self._q is None: + # Figure out q from available values, doing nothing others are not defined + if self._equatorial is not None: + self._q = self._equatorial2quat() + elif self._T is not None: + self._q = self._transform2quat() + return self._q + + # use property to make this get/set automatic + q = property(_get_q, _set_q) + + def _set_equatorial(self, equatorial): + """"""Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll] + expects values in degrees + bounds are not checked + + :param equatorial: list or array [ RA, Dec, Roll] in degrees + + """""" + att = np.array(equatorial) + ra, dec, roll = att + self._ra0 = ra + if ( ra > 180 ): + self._ra0 = ra - 360 + self._roll0 = roll + if ( roll > 180): + self._roll0 = roll - 360 + self._equatorial = att + + def _get_equatorial(self): + """"""Retrieve [RA, Dec, Roll] + + :rtype: numpy array + """""" + if self._equatorial is None: + if self._q is not None: + self._equatorial = self._quat2equatorial() + elif self._T is not None: + self._q = self._transform2quat() + self._equatorial = self._quat2equatorial() + return self._equatorial + + equatorial = property(_get_equatorial,_set_equatorial) + + def _get_ra(self): + """"""Retrieve RA term from equatorial system in degrees"""""" + return self.equatorial[0] + + def _get_dec(self): + """"""Retrieve Dec term from equatorial system in degrees"""""" + return self.equatorial[1] + + def _get_roll(self): + """"""Retrieve Roll term from equatorial system in degrees"""""" + return self.equatorial[2] + + ra = property(_get_ra) + dec = property(_get_dec) + roll = property(_get_roll) + + def _set_transform(self, T): + """""" + Set the value of the 3x3 rotation/transform matrix + + :param T: 3x3 array/numpy array + """""" + transform = np.array(T) + self._T = transform + + def _get_transform(self): + """""" + Retrieve the value of the 3x3 rotation/transform matrix + + :returns: 3x3 rotation/transform matrix + :rtype: numpy array + + """""" + if self._T is None: + if self._q is not None: + self._T = self._quat2transform() + elif self._equatorial is not None: + self._T = self._equatorial2transform() + return self._T + + transform = property(_get_transform, _set_transform) + + def _quat2equatorial(self): + """""" + Determine Right Ascension, Declination, and Roll for the object quaternion + + :returns: RA, Dec, Roll + :rtype: numpy array [ra,dec,roll] + """""" + + q = self.q + q2 = self.q**2 + + ## calculate direction cosine matrix elements from $quaternions + xa = q2[0] - q2[1] - q2[2] + q2[3] + xb = 2 * (q[0] * q[1] + q[2] * q[3]) + xn = 2 * (q[0] * q[2] - q[1] * q[3]) + yn = 2 * (q[1] * q[2] + q[0] * q[3]) + zn = q2[3] + q2[2] - q2[0] - q2[1] + + ##; calculate RA, Dec, Roll from cosine matrix elements + ra = degrees(atan2(xb , xa)) ; + dec = degrees(atan2(xn , sqrt(1 - xn**2))); + roll = degrees(atan2(yn , zn)) ; + if ( ra < 0 ): + ra += 360 + if ( roll < 0 ): + roll += 360 + + return np.array([ra, dec, roll]) + + + def _quat2transform(self): + """""" + Transform a unit quaternion into its corresponding rotation matrix (to + be applied on the right side). + + :returns: transform matrix + :rtype: numpy array + + """""" + x, y, z, w = self.q + xx2 = 2 * x * x + yy2 = 2 * y * y + zz2 = 2 * z * z + xy2 = 2 * x * y + wz2 = 2 * w * z + zx2 = 2 * z * x + wy2 = 2 * w * y + yz2 = 2 * y * z + wx2 = 2 * w * x + + rmat = np.empty((3, 3), float) + rmat[0,0] = 1. - yy2 - zz2 + rmat[0,1] = xy2 - wz2 + rmat[0,2] = zx2 + wy2 + rmat[1,0] = xy2 + wz2 + rmat[1,1] = 1. - xx2 - zz2 + rmat[1,2] = yz2 - wx2 + rmat[2,0] = zx2 - wy2 + rmat[2,1] = yz2 + wx2 + rmat[2,2] = 1. - xx2 - yy2 + + return rmat + + def _equatorial2quat( self ): + """"""Dummy method to return return quat. + + :returns: quaternion + :rtype: Quat + + """""" + return self._transform2quat() + + def _equatorial2transform( self ): + """"""Construct the transform/rotation matrix from RA,Dec,Roll + + :returns: transform matrix + :rtype: 3x3 numpy array + + """""" + ra = radians(self._get_ra()) + dec = radians(self._get_dec()) + roll = radians(self._get_roll()) + ca = cos(ra) + sa = sin(ra) + cd = cos(dec) + sd = sin(dec) + cr = cos(roll) + sr = sin(roll) + + # This is the transpose of the transformation matrix (related to translation + # of original perl code + rmat = np.array([[ca * cd, sa * cd, sd ], + [-ca * sd * sr - sa * cr, -sa * sd * sr + ca * cr, cd * sr], + [-ca * sd * cr + sa * sr, -sa * sd * cr - ca * sr, cd * cr]]) + + return rmat.transpose() + + def _transform2quat( self ): + """"""Construct quaternion from the transform/rotation matrix + + :returns: quaternion formed from transform matrix + :rtype: numpy array + """""" + + # Code was copied from perl PDL code that uses backwards index ordering + T = self.transform.transpose() + den = np.array([ 1.0 + T[0,0] - T[1,1] - T[2,2], + 1.0 - T[0,0] + T[1,1] - T[2,2], + 1.0 - T[0,0] - T[1,1] + T[2,2], + 1.0 + T[0,0] + T[1,1] + T[2,2]]) + + max_idx = np.flatnonzero(den == max(den))[0] + + q = np.zeros(4) + q[max_idx] = 0.5 * sqrt(max(den)) + denom = 4.0 * q[max_idx] + if (max_idx == 0): + q[1] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,0] + T[0,2]) / denom + q[3] = -(T[2,1] - T[1,2]) / denom + if (max_idx == 1): + q[0] = (T[1,0] + T[0,1]) / denom + q[2] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[0,2] - T[2,0]) / denom + if (max_idx == 2): + q[0] = (T[2,0] + T[0,2]) / denom + q[1] = (T[2,1] + T[1,2]) / denom + q[3] = -(T[1,0] - T[0,1]) / denom + if (max_idx == 3): + q[0] = -(T[2,1] - T[1,2]) / denom + q[1] = -(T[0,2] - T[2,0]) / denom + q[2] = -(T[1,0] - T[0,1]) / denom + + return q + + + def __div__(self, quat2): + """""" + Divide one quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> q = q1 / q2 + + Performs the operation as q1 * inverse q2 + + :returns: product q1 * inverse q2 + :rtype: Quat + + """""" + return self * quat2.inv() + + + def __mul__(self, quat2): + """""" + Multiply quaternion by another. + + Example usage:: + + >>> q1 = Quat((20,30,40)) + >>> q2 = Quat((30,40,50)) + >>> (q1 * q2).equatorial + array([ 349.73395729, 76.25393056, 127.61636727]) + + :returns: product q1 * q2 + :rtype: Quat + + """""" + q1 = self.q + q2 = quat2.q + mult = np.zeros(4) + mult[0] = q1[3]*q2[0] - q1[2]*q2[1] + q1[1]*q2[2] + q1[0]*q2[3] + mult[1] = q1[2]*q2[0] + q1[3]*q2[1] - q1[0]*q2[2] + q1[1]*q2[3] + mult[2] = -q1[1]*q2[0] + q1[0]*q2[1] + q1[3]*q2[2] + q1[2]*q2[3] + mult[3] = -q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] + q1[3]*q2[3] + return Quat(mult) + + def inv(self): + """""" + Invert the quaternion + + :returns: inverted quaternion + :rtype: Quat + """""" + return Quat([self.q[0], self.q[1], self.q[2], -self.q[3]]) + + +def normalize(array): + """""" + Normalize a 4 element array/list/numpy.array for use as a quaternion + + :param quat_array: 4 element list/array + :returns: normalized array + :rtype: numpy array + + """""" + quat = np.array(array) + return quat / np.sqrt(np.dot(quat, quat)) + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/ReadDump.py",".py","617","20","nData=[] +AData=[] +for i in range(0,1): + filename=""dump.img_post_minimize_""+str(i)+"".cfg"" + with open(filename, 'r') as fileData: + for j in range(0,7): + if(j==3): + nData.append(int(fileData.readline().strip())) + elif(j==6): + A=fileData.readline().strip().split(' ') + AData.append(float(A[0])*float(A[1])*-1) + else: + fileData.readline() + +filename = ""AreaAtoms.txt"" + +with open(filename, 'w') as fileData: + for i in range(0,1): + fileData.writelines(str(nData[i]) + "" "" + str(AData[i]) + ""\n"") +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/ReadLog.py",".py","251","13","from re import findall + +def read_log(): + log=open('log.lammps','r') + for i in log.readlines(): + t = i.find('GB energy') + if(t == 0): + Energy=i.split(' ') + GBEnergy = float(Energy[3]) + return GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/RunLammps.py",".py","1094","44","from Quaternion import Quat, normalize +from WriteLammps import write_lammps +from QuantFunc import QuatMat, find_orient, scale +from ReadLog import read_log +#from GenerateAtoms import GenerateAtoms +import os +#NOTE: axis must be along z of q1 +q1=normalize([0.4135, 0.5736, 0.4135, 0.5736]) +potential='Al99.eam.alloy' +element='Al' +temp=600 +tempDamp=0.01 +lattice=4.05 +minEng=-3.36 +A=[1,0,0] +typeAtom='fcc' +GBEnergy =[] +Theta = [] + +for theta in range(0,91): + q2=find_orient(theta, A, q1) + M1=scale(QuatMat(q1)) + M2=scale(QuatMat(q2)) + #M1=QuatMat(q1) + #M2=QuatMat(q2) + #print 2 + #GenerateAtoms(M1,M2) + write_lammps(M1,M2,potential,element,temp,tempDamp,theta,lattice,minEng,typeAtom) + t=os.system('mpirun -np 4 lmp_mpi < GB.in') + print t + GBEnergy.append(read_log()) + Theta.append(theta) + + +filename = str(element) + ""_"" + str(temp) + ""_Data_"" + str(A[0]) + str(A[1]) + str(A[2]) + "".txt"" + +with open(filename, 'w') as fileData: + for i in range(0,91): + fileData.writelines(str(Theta[i]) + "" "" + str(GBEnergy[i]) + ""\n"") + +print Theta, GBEnergy + + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/Python and Lammps/FullStackAll/FullStack555/Code/QuantFunc.py",".py","2244","90","from Quaternion import Quat, normalize +from math import cos, sin, radians, sqrt +from fractions import Fraction, gcd + +def QuatMat(q): + + qw=q[0] + qx=q[1] + qy=q[2] + qz=q[3] + + m11=1-(2*qy*qy)-(2*qz*qz) + m12=2*qx*qy-2*qz*qw + m13=2*qx*qz+2*qy*qw + + m21=2*qx*qy+2*qz*qw + m22=1-2*qx*qx-2*qz*qz + m23=2*qy*qz-2*qx*qw + + m31=2*qx*qz-2*qy*qw + m32=2*qy*qz+2*qx*qw + m33=1-2*qx*qx-2*qy*qy + + M=[[m11,m12,m13],[m21,m22,m23],[m31,m32,m33]] + + return M + +def QuatInv(q1): + + normsqr=q1[0]**2+q1[1]**2+q1[2]**2+q1[3]**3 + + q1inv=[q1[0]/normsqr,-q1[1]/normsqr,-q1[2]/normsqr,-q1[3]/normsqr] + + return q1inv + +def QuatMult(q1,q2): + + Q0 = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] + Q1 = q1[0]*q2[1] + q1[1]*q2[0] - q1[2]*q2[3] + q1[3]*q2[2] + Q2 = q1[0]*q2[2] + q1[1]*q2[3] + q1[2]*q2[0] - q1[3]*q2[1] + Q3 = q1[0]*q2[3] - q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[0] + + q=[Q0,Q1,Q2,Q3] + + return q + +def find_orient(theta,A,q1): + + qw= cos(radians(theta)/2.0) + qi=A[0]*sin(radians(theta)/2.0) + qj=A[1]*sin(radians(theta)/2.0) + qk=A[2]*sin(radians(theta)/2.0) + + q=normalize([qw,qi,qj,qk]) + qInv=normalize(QuatInv(q)) + q2=QuatMult(q1,qInv) + + return q2 + +def scale(M): + + x1=Fraction(M[0][0]).limit_denominator(20) + x2=Fraction(M[0][1]).limit_denominator(20) + x3=Fraction(M[0][2]).limit_denominator(20) + + X1=x1.numerator*x2.denominator*x3.denominator + X2=x2.numerator*x1.denominator*x3.denominator + X3=x3.numerator*x2.denominator*x1.denominator + + y1=Fraction(M[1][0]).limit_denominator(20) + y2=Fraction(M[1][1]).limit_denominator(20) + y3=Fraction(M[1][2]).limit_denominator(20) + + Y1=y1.numerator*y2.denominator*y3.denominator + Y2=y2.numerator*y1.denominator*y3.denominator + Y3=y3.numerator*y2.denominator*y1.denominator + + z1=Fraction(M[2][0]).limit_denominator(20) + z2=Fraction(M[2][1]).limit_denominator(20) + z3=Fraction(M[2][2]).limit_denominator(20) + + Z1=z1.numerator*z2.denominator*z3.denominator + Z2=z2.numerator*z1.denominator*z3.denominator + Z3=z3.numerator*z2.denominator*z1.denominator + + M=[[X1,X2,X3],[Y1,Y2,Y3],[Z1,Z2,Z3]] + + return M + +","Python" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/MATLAB/Result.m",".m","433","24","dataElm=importdata('Al_0_Data_100.txt'); +dataGen=importdata('AreaAtoms.txt'); +K1=dataElm(:,2); +Theta=dataElm(:,1); +K1new=[0;K1(2:90);0]; +%plot(Theta,K1new); +PureEng=-3.36; +n=dataGen(:,1); +A=dataGen(:,2); + +TotalEng=K1.*A+PureEng.*n; + +ActEng=TotalEng(1)/n(1); + +K2=(TotalEng-ActEng.*n)./A; +plot(Theta,K1); +figure(); +plot(Theta,K2); +figure(); +plot(Theta,K1new); +%plot(Theta,K2,'b',Theta,K1,'r',Theta,K1new,'g'); + + +","MATLAB" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/MATLAB/PlotsAll.m",".m","1969","67","clear +clc + +Al_0_5=importdata('Al_0_Data_100.txt'); +%Al_300_5=importdata('Al_300_Data_100.txt'); %Negative +%Al_600_5=importdata('Al_600_Data_100.txt'); %Negative +AlEng5=Al_0_5(:,2); + +Al_0_10=importdata('Al_0_Data_100_large.txt'); +AlEng10=Al_0_10(:,2); + + +Cu_0_5=importdata('Cu_0_Data_100.txt'); +%Cu_300_5=importdata('Cu_300_Data_100.txt'); Negative +%Cu_600_5=importdata('Cu_600_Data_100.txt'); Negative +CuEng5=Cu_0_5(:,2); + +Fe_0_5=importdata('Fe_0_Data_100.txt'); +%Fe_300_5=importdata('Fe_300_Data_100.txt'); Error +%Fe_600_5=importdata('Fe_600_Data_100.txt'); Error +FeEng5=Fe_0_5(:,2); + +Ni_0_5=importdata('Ni_0_Data_100.txt'); +%Ni_300_5=importdata('Ni_300_Data_100.txt'); +%Ni_600_5=importdata('Ni_600_Data_100.txt'); Negative +NiEng5=Ni_0_5(:,2); +%Ni300Eng5=Ni_300_5(:,2); + +Na_0_5=importdata('Na_0_Data_100.txt'); +%Na_300_5=importdata('Na_300_Data_100.txt'); Negative +%Na_600_5=importdata('Na_600_Data_100.txt'); Negative +NaEng5=Na_0_5(:,2); + +Theta=0:1:90; + +%plot(Theta,AlEng5,'g', Theta, FeEng5, 'r-', Theta, NiEng5,'k', Theta, NaEng5,'b', Theta, CuEng5,'m'); +%plot(Theta,NiEng5,Theta,Ni300Eng5); +mNi=polyfit(AlEng5,NiEng5,1); +mCu=polyfit(AlEng5,CuEng5,1); +mNa=polyfit(AlEng5,NaEng5,1); +mFe=polyfit(AlEng5,FeEng5,1); + +hold on; + +%scatter(AlEng5, AlEng5) +%plot(AlEng5,AlEng5); + +scatter( AlEng5, NiEng5,'r') +plot(AlEng5,(mNi(1).*AlEng5+ mNi(2)),'k'); + +scatter( AlEng5, CuEng5,'b') +plot(AlEng5,(mCu(1).*AlEng5+ mCu(2)),'k'); + +%scatter(AlEng5, NaEng5,'r') +%plot(AlEng5,(mNa(1).*AlEng5+ mNa(2)),'k'); + +%scatter(AlEng5, FeEng5,'b') +%plot(AlEng5,(mFe(1).*AlEng5+ mFe(2)),'k'); + +axis([300 1100 -100 3200]); +set(gca,'FontSize',16); +%title('Grain Boundary Energy vs Misorientation'); +xlabel('GB Energy of Al (mJ/m^2)'); +ylabel('GB Energy of FCC elements (mJ/m^2)'); +h=legend('Ni - Al ','Ni - Al fit ','Cu - Al','Cu - Al fit'); +%set(legend,'FontSize',16,'Orientation','horizontal'); +%h.Orientation = 'horizontal';","MATLAB" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/MATLAB/specgrain.m",".m","843","33","clear +clc +GBEValues=importdata('GBEValues.csv'); +Data=GBEValues.data; +TextData=GBEValues.textdata; + +DataEng=Data(:,1); +DataTheta=Data(:,2); + +AlEng=DataEng(1:16,1); +CuEng=DataEng(17:32,1); +NiEng=DataEng(33:48,1); + +AlTheta=DataTheta(1:16,1); +CuTheta=DataTheta(17:32,1); +NiTheta=DataTheta(33:48,1); +position=[NiEng(2:15)+200, NiTheta(2:15)]; +hold on; +axis([0 90 0 3000]); +set(gca,'FontSize',16); +scatter(AlTheta,AlEng,'r','s','filled'); +scatter(CuTheta,CuEng,'b','s','filled'); +scatter(NiTheta,NiEng,'g','s','filled'); + +line(AlTheta,AlEng,'Color','r'); +line(CuTheta,CuEng,'Color','b'); +line(NiTheta,NiEng,'Color','g'); +xlabel('Misorientation Angle (degrees)'); +ylabel('GB Energy (mJ/m^2)'); +legend('Al','Cu','Ni'); +%for i=1:14 +%text(NiTheta(i+1),NiEng(i+1),TextData(i+1,5),'VerticalAlignment','top','Position',[position(i,2) position(i,1)]); +%end","MATLAB" +"Multi-scale modeling","vishalsubbiah/Grain-Boundary-Energies-LAMMPS","Code and Scripts/MATLAB/angle.m",".m","405","18","m1=[-1 2 0;0 0 1; 2 1 0]; +m2=[-5 10 8;8 -16 25; 2 1 0]; +m1(1,:)=m1(1,:)./norm(m1(1,:)); +m1(2,:)=m1(2,:)./norm(m1(2,:)); +m1(3,:)=m1(3,:)./norm(m1(3,:)); + +m2(1,:)=m2(1,:)./norm(m2(1,:)); +m2(2,:)=m2(2,:)./norm(m2(2,:)); +m2(3,:)=m2(3,:)./norm(m2(3,:)); + +m=m1*pinv(m2); + +m(1,:)=m(1,:)./norm(m(1,:)); +m(2,:)=m(2,:)./norm(m(2,:)); +m(3,:)=m(3,:)./norm(m(3,:)); + +a=vrrotmat2vec(m); +sol=a(4)*180/pi","MATLAB" +"Multi-scale modeling","vivek231/Skin-Project","train.py",".py","6685","157","from __future__ import print_function +import argparse +import os +from math import log10 +import torch +import torch.nn as nn +import torch.optim as optim +from torch.autograd import Variable +from torch.utils.data import DataLoader +from model import G,D +from data import get_training_set, get_test_set +import torch.backends.cudnn as cudnn +from loss import EPE + +# ===========================Training settings========================= +parser = argparse.ArgumentParser(description='FCANet-PyTorch-implementation') +parser.add_argument('--dataset', required=True, help='skin') +parser.add_argument('--batchSize', type=int, default=2, help='training batch size') +parser.add_argument('--testBatchSize', type=int, default=2, help='testing batch size') +parser.add_argument('--nEpochs', type=int, default=200, help='number of epochs to train for') +parser.add_argument('--input_nc', type=int, default=3, help='input image channels') +parser.add_argument('--output_nc', type=int, default=3, help='output image channels') +parser.add_argument('--ngf', type=int, default=64, help='generator filters in first conv layer') +parser.add_argument('--ndf', type=int, default=64, help='discriminator filters in first conv layer') +parser.add_argument('--lr', type=float, default=0.0002, help='Learning Rate. Default=0.002') +parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5') +parser.add_argument('--cuda', action='store_true', help='use cuda?') +parser.add_argument('--threads', type=int, default=4, help='number of threads for data loader to use') +parser.add_argument('--seed', type=int, default=123, help='random seed to use. Default=123') +parser.add_argument('--lamb', type=int, default=100, help='weight on L1 term in objective') +opt = parser.parse_args() + +print(opt) + +if opt.cuda and not torch.cuda.is_available(): + raise Exception(""No GPU found, please run without --cuda"") +cudnn.benchmark = True +torch.manual_seed(opt.seed) +if opt.cuda: + torch.cuda.manual_seed(opt.seed) +#=============== Load the images from the folder============== +print('===> Loading datasets') +root_path = ""dataset/"" +train_set = get_training_set(root_path + opt.dataset) +test_set = get_test_set(root_path + opt.dataset) +training_data_loader = DataLoader(dataset=train_set, num_workers=opt.threads, batch_size=opt.batchSize, shuffle=True) +testing_data_loader = DataLoader(dataset=test_set, num_workers=opt.threads, batch_size=opt.testBatchSize, shuffle=False) +# ======= Load the Generator and Discriminator =============== +print('===> Building model') +netG = G(opt.input_nc, opt.output_nc, opt.ngf) +pytorch_total_params = sum(p.numel() for p in netG.parameters() if p.requires_grad) +print (""\nTrainable parameters"", pytorch_total_params) +netD = D(opt.input_nc, opt.output_nc, opt.ndf) +#========Loss Function========== +criterion = nn.BCELoss() +criterion_l1 = nn.L1Loss() +criterion_mse = nn.MSELoss() +#================================ +real_A = torch.FloatTensor(opt.batchSize, opt.input_nc, 128, 128) +real_B = torch.FloatTensor(opt.batchSize, opt.output_nc, 128, 128) +label = torch.FloatTensor(opt.batchSize) +real_label = 1 +fake_label = 0 + +if opt.cuda: + netD = netD.cuda() + netG = netG.cuda() + criterion = criterion.cuda() + criterion_l1 = criterion_l1.cuda() + criterion_mse = criterion_mse.cuda() + real_A = real_A.cuda() + real_B = real_B.cuda() + label = label.cuda() + +real_A = Variable(real_A) +real_B = Variable(real_B) +label = Variable(label) + +# ==========setup optimizer=============== +optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) +optimizerG = optim.Adam(netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) + +def train(epoch): + for iteration, batch in enumerate(training_data_loader, 1): + ############################ + # (1) Update D network: maximize log(D(x,y)) + log(1 - D(x,G(x))) + ########################### + # train with real + netD.volatile = False + netD.zero_grad() + real_a_cpu, real_b_cpu = batch[0], batch[1] + real_A.data.resize_(real_a_cpu.size()).copy_(real_a_cpu) + real_B.data.resize_(real_b_cpu.size()).copy_(real_b_cpu) + + output = netD(torch.cat((real_A, real_B), 1)) + label.data.resize_(output.size()).fill_(real_label) + err_d_real = criterion(output, label) + err_d_real.backward() + d_x_y = output.data.mean() + + # train with fake + fake_b = netG(real_A) + output = netD(torch.cat((real_A, fake_b.detach()), 1)) + label.data.resize_(output.size()).fill_(fake_label) + err_d_fake = criterion(output, label) + err_d_fake.backward() + d_x_gx = output.data.mean() + err_d = (err_d_real + err_d_fake) / 2.0 + optimizerD.step() + + ############################ + # (2) Update G network: maximize log(D(x,G(x))) + L1(y,G(x)) + ########################### + netG.zero_grad() + netD.volatile = True + output = netD(torch.cat((real_A, fake_b), 1)) + label.data.resize_(output.size()).fill_(real_label) + err_g = criterion(output, label) + opt.lamb * criterion_l1(fake_b, real_B)+50*EPE(fake_b, real_B) + err_g.backward() + d_x_gx_2 = output.data.mean() + optimizerG.step() + + print(""===> Epoch[{}]({}/{}): Loss_D: {:.4f} Loss_G: {:.4f} D(x): {:.4f} D(G(z)): {:.4f}/{:.4f}"".format( + epoch, iteration, len(training_data_loader), err_d.data[0], err_g.data[0], d_x_y, d_x_gx, d_x_gx_2)) + +def test(): + avg_psnr = 0 + for batch in testing_data_loader: + input, target = Variable(batch[0]), Variable(batch[1]) + if opt.cuda: + input = input.cuda() + target = target.cuda() + + prediction = netG(input) + mse = criterion_mse(prediction, target) + psnr = 10 * log10(1 / mse.data[0]) + avg_psnr += psnr + print(""===> Avg. PSNR: {:.4f} dB"".format(avg_psnr / len(testing_data_loader))) + +# ===========Save the checkpoints======== +def checkpoint(epoch): + if not os.path.exists(""checkpoint""): + os.mkdir(""checkpoint"") + if not os.path.exists(os.path.join(""checkpoint"", opt.dataset)): + os.mkdir(os.path.join(""checkpoint"", opt.dataset)) + net_g_model_out_path = ""checkpoint/{}/netG_model_epoch_{}.pth"".format(opt.dataset, epoch) + net_d_model_out_path = ""checkpoint/{}/netD_model_epoch_{}.pth"".format(opt.dataset, epoch) + torch.save(netG.state_dict(), net_g_model_out_path) + torch.save(netD.state_dict(), net_d_model_out_path) + print(""Checkpoint saved to {}"".format(""checkpoint"" + opt.dataset)) + +for epoch in range(1, opt.nEpochs + 1): + train(epoch) + test() + if epoch % 1 == 0: + checkpoint(epoch) +","Python" +"Multi-scale modeling","vivek231/Skin-Project","loss.py",".py","9677","318","import torch +import numpy as np +import pytorch_ssim +from skimage import filters +from skimage.color import rgb2gray +import torch.nn.functional as F +import torch.autograd.variable as Variable + +try: + from itertools import ifilterfalse +except ImportError: # py3k + from itertools import filterfalse as ifilterfalse + +def myssim_loss(inp,target): + inp = inp.cuda() + target = target.cuda() + ssim_loss = pytorch_ssim.SSIM(window_size = 11) + ssim_loss.cuda() + ssim_total=1-ssim_loss(inp, target) + + return ssim_total + +def logDepth(x): + + x = torch.clamp(x , 1.0/255.0) + return 0.179581 * torch.log(x) + 1 + +def ScaleInvariantMeanSquaredError(output, gt): + output = logDepth(output / 10.0) * 10.0 + gt = logDepth(gt / 10.0) * 10.0 + d = output - gt + diff = torch.mean(d * d) + s = int(np.prod(d.size())) + relDiff = (d.sum() * d.sum()) / (s * s) + return diff - relDiff + +def AbsoluteRelativeDifference(output, gt): + gt = torch.max(gt, 1.0 / 255.0) + diff = torch.mean(torch.abs(output - gt) / gt) + return diff + +def MVNError(output, gt): + outMean = torch.mean(output) + outStd = torch.std(output) + output = (output - outMean)/outStd + gtMean = torch.mean(gt) + gtStd = torch.std(gt) + gt = (gt - gtMean)/gtStd + d = output - gt + diff = torch.sqrt(torch.mean(d * d)) + return diff + +def dice_loss(input,target): + num=input*target + # print (num.size()) + num=torch.sum(num,dim=2) + # print (num.size()) + num=torch.sum(num,dim=2) + # print (num.size()) + + den1=input*input + den1=torch.sum(den1,dim=2) + den1=torch.sum(den1,dim=2) + + den2=target*target + den2=torch.sum(den2,dim=2) + den2=torch.sum(den2,dim=2) + + dice=2*(num/(den1+den2)) + + dice_total=1-1*torch.sum(dice)/dice.size(0)#divide by batchsize + + return dice_total + +def EPE(predicted_edge, gt_edge, sparse=False, mean=True): + EPE_map = torch.norm(gt_edge-predicted_edge,2,1) + if sparse: + EPE_map = EPE_map[gt_edge != 0] + if mean: + return EPE_map.mean() + else: + return EPE_map.sum() + +def getEdge(batch): + edgeslist=[] + for kk in range(batch.size(0)): + x=batch[kk] + # print(x.size()) + x=x.cpu().data.numpy() + if len(x.shape)>2: + x=np.transpose(x,(1,2,0)) + x=rgb2gray(x) + edges = filters.sobel(x) + edgeslist.append(edges) + edgeslist=np.array(edgeslist) + edgeslist=torch.Tensor(edgeslist).cuda() + edgeslist=Variable(edgeslist) + return edgeslist + +def lovasz_grad(gt_sorted): + """""" + Computes gradient of the Lovasz extension w.r.t sorted errors + See Alg. 1 in paper + """""" + p = len(gt_sorted) + gts = gt_sorted.sum() + intersection = gts - gt_sorted.float().cumsum(0) + union = gts + (1 - gt_sorted).float().cumsum(0) + jaccard = 1. - intersection / union + if p > 1: # cover 1-pixel case + jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] + return jaccard + + +def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True): + """""" + IoU for foreground class + binary: 1 foreground, 0 background + """""" + if not per_image: + preds, labels = (preds,), (labels,) + ious = [] + for pred, label in zip(preds, labels): + intersection = ((label == 1) & (pred == 1)).sum() + union = ((label == 1) | ((pred == 1) & (label != ignore))).sum() + if not union: + iou = EMPTY + else: + iou = float(intersection) / union + ious.append(iou) + iou = mean(ious) # mean accross images if per_image + return 100 * iou + + +def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False): + """""" + Array of IoU for each (non ignored) class + """""" + if not per_image: + preds, labels = (preds,), (labels,) + ious = [] + for pred, label in zip(preds, labels): + iou = [] + for i in range(C): + if i != ignore: # The ignored label is sometimes among predicted classes (ENet - CityScapes) + intersection = ((label == i) & (pred == i)).sum() + union = ((label == i) | ((pred == i) & (label != ignore))).sum() + if not union: + iou.append(EMPTY) + else: + iou.append(float(intersection) / union) + ious.append(iou) + ious = map(mean, zip(*ious)) # mean accross images if per_image + return 100 * np.array(ious) + + +# --------------------------- BINARY LOSSES --------------------------- + + +def lovasz_hinge(logits, labels, per_image=True, ignore=None): + """""" + Binary Lovasz hinge loss + logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) + labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) + per_image: compute the loss per image instead of per batch + ignore: void class id + """""" + if per_image: + loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore)) + for log, lab in zip(logits, labels)) + else: + loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)) + return loss + + +def lovasz_hinge_flat(logits, labels): + """""" + Binary Lovasz hinge loss + logits: [P] Variable, logits at each prediction (between -\infty and +\infty) + labels: [P] Tensor, binary ground truth labels (0 or 1) + ignore: label to ignore + """""" + if len(labels) == 0: + # only void pixels, the gradients should be 0 + return logits.sum() * 0. + signs = 2. * labels.float() - 1. + errors = (1. - logits * Variable(signs)) + errors_sorted, perm = torch.sort(errors, dim=0, descending=True) + perm = perm.data + gt_sorted = labels[perm] + grad = lovasz_grad(gt_sorted) + loss = torch.dot(F.relu(errors_sorted), Variable(grad)) + return loss + + +def flatten_binary_scores(scores, labels, ignore=None): + """""" + Flattens predictions in the batch (binary case) + Remove labels equal to 'ignore' + """""" + scores = scores.view(-1) + labels = labels.view(-1) + if ignore is None: + return scores, labels + valid = (labels != ignore) + vscores = scores[valid] + vlabels = labels[valid] + return vscores, vlabels + + +class StableBCELoss(torch.nn.modules.Module): + def __init__(self): + super(StableBCELoss, self).__init__() + def forward(self, input, target): + neg_abs = - input.abs() + loss = input.clamp(min=0) - input * target + (1 + neg_abs.exp()).log() + return loss.mean() + + +def binary_xloss(logits, labels, ignore=None): + + logits, labels = flatten_binary_scores(logits, labels, ignore) + loss = StableBCELoss()(logits, Variable(labels.float())) + return loss + + +# --------------------------- MULTICLASS LOSSES --------------------------- + + +def lovasz_softmax(probas, labels, only_present=False, per_image=False, ignore=None): + """""" + Multi-class Lovasz-Softmax loss + probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1) + labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1) + only_present: average only on classes present in ground truth + per_image: compute the loss per image instead of per batch + ignore: void class labels + """""" + if per_image: + loss = mean(lovasz_softmax_flat(*flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore), only_present=only_present) + for prob, lab in zip(probas, labels)) + else: + loss = lovasz_softmax_flat(*flatten_probas(probas, labels, ignore), only_present=only_present) + return loss + + +def lovasz_softmax_flat(probas, labels, only_present=False): + """""" + Multi-class Lovasz-Softmax loss + probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) + labels: [P] Tensor, ground truth labels (between 0 and C - 1) + only_present: average only on classes present in ground truth + """""" + if probas.numel() == 0: + # only void pixels, the gradients should be 0 + return probas * 0. + C = probas.size(1) + + C = probas.size(1) + losses = [] + for c in range(C): + fg = (labels == c).float() # foreground for class c + if only_present and fg.sum() == 0: + continue + errors = (Variable(fg) - probas[:, c]).abs() + errors_sorted, perm = torch.sort(errors, 0, descending=True) + perm = perm.data + fg_sorted = fg[perm] + losses.append(torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted)))) + return mean(losses) + + +def flatten_probas(probas, labels, ignore=None): + """""" + Flattens predictions in the batch + """""" + B, C, H, W = probas.size() + probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C + labels = labels.view(-1) + if ignore is None: + return probas, labels + valid = (labels != ignore) + vprobas = probas[valid.nonzero().squeeze()] + vlabels = labels[valid] + return vprobas, vlabels + +def xloss(logits, labels, ignore=None): + """""" + Cross entropy loss + """""" + return F.cross_entropy(logits, Variable(labels), ignore_index=255) + + +# --------------------------- HELPER FUNCTIONS --------------------------- +def isnan(x): + return x != x + + +def mean(l, ignore_nan=True, empty=0): + """""" + nanmean compatible with generators. + """""" + l = iter(l) + if ignore_nan: + l = ifilterfalse(isnan, l) + try: + n = 1 + acc = next(l) + except StopIteration: + if empty == 'raise': + raise ValueError('Empty mean') + return empty + for n, v in enumerate(l, 2): + acc += v + if n == 1: + return acc + return acc / n +","Python" +"Multi-scale modeling","vivek231/Skin-Project","model.py",".py","6629","159","# Code written and maintained by Vivek Kumar Singh. +# Universitat Rovira I Virgili, Tarragona Spain +# Date: 01/June/2019 +from __future__ import print_function +from collections import OrderedDict +import torch +import torch.nn as nn +import cv2 +import numpy as np +import torch.nn.functional as F +from FCA import FCANet + +# For input size input_nc x 128 x 128 +class G(nn.Module): + def __init__(self, input_nc, output_nc, ngf): + super(G, self).__init__() + self.size1 = nn.AvgPool2d(1, stride=8) + self.size2 = nn.AvgPool2d(1, stride=4) + self.size3 = nn.AvgPool2d(1, stride=2) + self.convinput = nn.Conv2d(3, ngf, kernel_size=3,padding=1, bias=False) + self.factor_in = FCANet(ngf,ngf) + self.conva = nn.Conv2d(3, ngf, kernel_size=3,padding=1, bias=False) + self.factor_a = FCANet(ngf,ngf) + self.convb = nn.Conv2d(3, ngf, kernel_size=3,padding=1, bias=False) + self.factor_b = FCANet(ngf,ngf) + self.convc = nn.Conv2d(3, ngf, kernel_size=3,padding=1, bias=False) + self.factor_c = FCANet(ngf,ngf) + + self.conv1 = nn.Conv2d(ngf, ngf, 4, 2, 1) + self.conv2 = nn.Conv2d(ngf, ngf * 2, 4, 2, 1) + self.c2 = FCANet(ngf*2,ngf*2) + self.conv3 = nn.Conv2d(ngf * 2, ngf * 4, 4, 2, 1) + self.c3 = FCANet(ngf*4,ngf*4) + self.conv4 = nn.Conv2d(ngf * 4, ngf * 8, 4, 2, 1) + self.c4 = FCANet(ngf*8,ngf*8) + self.conv5 = nn.Conv2d(ngf * 8, ngf * 8, 4, 2, 1) + self.c5 = FCANet(ngf*8,ngf*8) + self.conv6 = nn.Conv2d(ngf * 8, ngf * 8, 4, 2, 1) + self.c6 = FCANet(ngf*8,ngf*8) + self.conv7 = nn.Conv2d(ngf * 8, ngf * 8, 4, 2, 1) + self.c7 = FCANet(ngf*8,ngf*8) + + self.dconv1 = nn.ConvTranspose2d(ngf * 8, ngf * 8, 4, 2, 1) + self.dconv2 = nn.ConvTranspose2d(ngf * 8 * 2, ngf * 8, 4, 2, 1) + self.dconv3 = nn.ConvTranspose2d(ngf * 8 * 2, ngf * 8, 4, 2, 1) + self.dconv4 = nn.ConvTranspose2d(ngf * 8 * 2, ngf * 4, 4, 2, 1) + self.dconv5 = nn.ConvTranspose2d(ngf * 4 * 2, ngf * 2 , 4, 2, 1) + self.dconv6 = nn.ConvTranspose2d(ngf*4, ngf, 4, 2, 1) + self.dconv7 = nn.ConvTranspose2d(ngf*2, output_nc, 4, 2, 1) + + self.batch_norm = nn.BatchNorm2d(ngf) + self.batch_norm2 = nn.BatchNorm2d(ngf * 2) + self.batch_norm4 = nn.BatchNorm2d(ngf * 4) + self.batch_norm8 = nn.BatchNorm2d(ngf * 8) + self.leaky_relu = nn.LeakyReLU(0.2, True) + self.relu = nn.ReLU(True) + self.dropout = nn.Dropout(0.5) + self.tanh = nn.Tanh() + + def forward(self, input): + + a = self.size1(input) + b = self.size2(input) + c = self.size3(input) + input = self.convinput(input) + input = self.factor_in(input) + a = self.conva(a) + a = self.factor_a(a) + a = nn.functional.interpolate(a, size=128, mode='bilinear', align_corners=True) + b = self.convb(b) + b = self.factor_b(b) + b = nn.functional.interpolate(b, size=128, mode='bilinear', align_corners=True) + c = self.convc(c) + c = self.factor_c(c) + c = nn.functional.interpolate(c, size=128, mode='bilinear', align_corners=True) +# ================ Addition of all the multiscale features============ + x = (input+a+b+c) + e1 = self.conv1(x) + e2 = self.batch_norm2(self.conv2(self.leaky_relu(e1))) + e2 = self.c2(e2) + e3 = self.batch_norm4(self.conv3(self.leaky_relu(e2))) + e3 = self.c3(e3) + e4 = self.batch_norm8(self.conv4(self.leaky_relu(e3))) + e4 = self.c4(e4) + e5 = self.batch_norm8(self.conv5(self.leaky_relu(e4))) + e5 = self.c5(e5) + e6 = self.batch_norm8(self.conv6(self.leaky_relu(e5))) + e6 = self.c6(e6) + e7 = self.conv7(self.leaky_relu(e6)) + e7 = self.c7(e7) + print (""================================"") + + + # Decoder + + d1_ = self.dropout(self.batch_norm8(self.dconv1(self.relu(e7)))) + d1 = torch.cat((d1_, e6), 1) + d2_ = self.dropout(self.batch_norm8(self.dconv2(self.relu(d1)))) + d2 = torch.cat((d2_, e5), 1) + d3_ = self.dropout(self.batch_norm8(self.dconv3(self.relu(d2)))) + d3 = torch.cat((d3_, e4), 1) + d4_ = self.batch_norm4(self.dconv4(self.relu(d3))) + d4 = torch.cat((d4_, e3), 1) + d5_ = self.batch_norm2(self.dconv5(self.relu(d4))) + d5 = torch.cat((d5_, e2), 1) + d6_ = self.batch_norm(self.dconv6(self.relu(d5))) + d6 = torch.cat((d6_, e1), 1) + d7 = self.dconv7(self.relu(d6)) + output = self.tanh(d7) + return output + +class D(nn.Module): + def __init__(self, input_nc, output_nc, ndf): + super(D, self).__init__() + self.s1 = nn.AvgPool2d(1, stride=8) + self.s2 = nn.AvgPool2d(1, stride=4) + self.s3 = nn.AvgPool2d(1, stride=2) + self.convinput = nn.Conv2d(input_nc + output_nc, ndf, kernel_size=3,padding=1, bias=False) + self.factor_in = FCANet(ndf,ndf) + self.conva=nn.Conv2d(input_nc + output_nc, ndf, kernel_size=3,padding=1, bias=False) + self.factor_a = FCANet(ndf,ndf) + self.convb=nn.Conv2d(input_nc + output_nc, ndf, kernel_size=3,padding=1, bias=False) + self.factor_b = FCANet(ndf,ndf) + self.convc=nn.Conv2d(input_nc + output_nc, ndf, kernel_size=3,padding=1, bias=False) + self.factor_c = FCANet(ndf,ndf) + self.conv1 = nn.Conv2d(ndf, ndf, 4, 2, 1) + self.d1 = FCANet(ndf,ndf) + self.conv2 = nn.Conv2d(ndf, 1, 4, 2, 1) + + self.batch_norm2 = nn.BatchNorm2d(ndf * 2) + self.batch_norm4 = nn.BatchNorm2d(ndf * 4) + self.batch_norm8 = nn.BatchNorm2d(ndf * 8) + self.leaky_relu = nn.LeakyReLU(0.2, True) + self.sigmoid = nn.Sigmoid() + + def forward(self, input): + + a = self.s1(input) + b = self.s2(input) + c = self.s3(input) + input = self.convinput(input) + input = self.factor_in(input) + a = self.conva(a) + a = self.factor_a(a) + a = nn.functional.interpolate(a, size=128, mode='bilinear', align_corners=True) + b = self.convc(b) + b = self.factor_c(b) + b = nn.functional.interpolate(b, size=128, mode='bilinear', align_corners=True) + c = self.convd(c) + c = self.factor_d(c) + c = nn.functional.interpolate(c, size=128, mode='bilinear', align_corners=True) +# ================== Addition of all scales features =================== + x = (input+a+b+c) + h1 = self.conv1(x) + h1 = self.d1(h1) + h2 = self.conv2(self.leaky_relu(h1)) + output = self.sigmoid(h2) + return output +","Python" +"Multi-scale modeling","vivek231/Skin-Project","dataset.py",".py","718","25","from os import listdir +from os.path import join + +import torch.utils.data as data + +from util import is_image_file, load_img + + +class DatasetFromFolder(data.Dataset): + def __init__(self, image_dir): + super(DatasetFromFolder, self).__init__() + self.a_path = join(image_dir, ""a"") + self.b_path = join(image_dir, ""b"") + self.image_filenames = [x for x in listdir(self.a_path) if is_image_file(x)] + + def __getitem__(self, index): + # Load Image + input = load_img(join(self.a_path, self.image_filenames[index])) + target = load_img(join(self.b_path, self.image_filenames[index])) + + return input, target + + def __len__(self): + return len(self.image_filenames) +","Python" +"Multi-scale modeling","vivek231/Skin-Project","FCA.py",".py","5603","130","from __future__ import division +import os +import numpy as np +import torch +import torch.nn.functional as F +import torch.nn as nn +from torch.nn.functional import upsample,normalize +from torch.nn import Module, Sequential, Conv2d, ReLU,AdaptiveMaxPool2d, AdaptiveAvgPool2d, \ +NLLLoss, BCELoss, CrossEntropyLoss, AvgPool2d, MaxPool2d, Parameter, Linear, Sigmoid, Softmax, Dropout, Embedding +from collections import OrderedDict + +class CAM_Module(Module): + """""" Channel attention module"""""" + def __init__(self, in_dim): + super(CAM_Module, self).__init__() + self.chanel_in = in_dim + self.gamma = Parameter(torch.zeros(1)) + self.softmax = Softmax(dim=-1) + def forward(self,x): + """""" + inputs : + x : input feature maps( B X C X H X W) + returns : + out : attention value + input feature + attention: B X C X C + """""" + m_batchsize, C, height, width = x.size() + proj_query = x.view(m_batchsize, C, -1) + proj_key = x.view(m_batchsize, C, -1).permute(0, 2, 1) + energy = torch.bmm(proj_query, proj_key) + energy_new = torch.max(energy, -1, keepdim=True)[0].expand_as(energy)-energy + attention = self.softmax(energy_new) + proj_value = x.view(m_batchsize, C, -1) + out = torch.bmm(attention, proj_value) + out = out.view(m_batchsize, C, height, width) + out = self.gamma*out# + x + return out + +class non_bottleneck_1d (nn.Module): + def __init__(self, chann, dropprob, dilated): + super().__init__() + self.conv3x1_1 = nn.Conv2d(chann, chann, (3, 1), stride=1, padding=(1,0), bias=True) + self.conv1x3_1 = nn.Conv2d(chann, chann, (1,3), stride=1, padding=(0,1), bias=True) + self.bn1 = nn.BatchNorm2d(chann, eps=1e-03) + self.conv3x1_2 = nn.Conv2d(chann, chann, (3, 1), stride=1, padding=(1*dilated,0), bias=True, dilation = (dilated,1)) + self.conv1x3_2 = nn.Conv2d(chann, chann, (1,3), stride=1, padding=(0,1*dilated), bias=True, dilation = (1, dilated)) + self.bn2 = nn.BatchNorm2d(chann, eps=1e-03) + self.dropout = nn.Dropout2d(dropprob) + + def forward(self, input): + + output = self.conv3x1_1(input) + output = F.relu(output) + output = self.conv1x3_1(output) + output = self.bn1(output) + output = F.relu(output) + output = self.conv3x1_2(output) + output = F.relu(output) + output = self.conv1x3_2(output) + output = self.bn2(output) + + if (self.dropout.p != 0): + output = self.dropout(output) + + return F.relu(output+input) + +class PAM_Module(Module): + """""" Position attention module"""""" + #Ref from SAGAN + def __init__(self, in_dim): + super(PAM_Module, self).__init__() + self.chanel_in = in_dim + self.query_conv = Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1) + self.key_conv = Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1) + self.value_conv = Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1) + self.gamma = Parameter(torch.zeros(1)) + self.softmax = Softmax(dim=-1) + + def forward(self, x): + """""" + inputs : + x : input feature maps( B X C X H X W) + returns : + out : attention value + input feature + attention: B X (HxW) X (HxW) + """""" + m_batchsize, C, height, width = x.size() + proj_query = self.query_conv(x).view(m_batchsize, -1, width*height).permute(0, 2, 1) + proj_key = self.key_conv(x).view(m_batchsize, -1, width*height) + energy = torch.bmm(proj_query, proj_key) + attention = self.softmax(energy) + proj_value = self.value_conv(x).view(m_batchsize, -1, width*height) + out = torch.bmm(proj_value, attention.permute(0, 2, 1)) + out = out.view(m_batchsize, C, height, width) + out = self.gamma*out + return out + +class FCANet(nn.Module): + def __init__(self, in_channels, out_channels): + super(FCANet, self).__init__() + inter_channels = in_channels // 4 + self.conv5a = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU()) + self.conv5c = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU()) + self.sa = non_bottleneck_1d(inter_channels, 0.3, 2) + self.sc = CAM_Module(inter_channels) + self.conv51 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU()) + self.conv52 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU()) + self.conv8 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(inter_channels, out_channels, 1)) + + def forward(self, x): + feat1 = self.conv5a(x) + sa_feat = self.sa(feat1) + sa_conv = self.conv51(sa_feat) + feat2 = self.conv5c(x) + sc_feat = self.sc(feat2) + sc_conv = self.conv52(sc_feat) + feat_sum = 0.3*sa_conv+0.7*sc_conv + sasc_output = self.conv8(feat_sum) + return sasc_output + + +","Python" +"Multi-scale modeling","vivek231/Skin-Project","test.py",".py","1804","53","from __future__ import print_function +import argparse +import os + +import torch +from torch.autograd import Variable +import numpy as np +from models import G +from util import is_image_file, load_img, save_img + +# Testing settings +parser = argparse.ArgumentParser(description='FCANet-PyTorch-implementation') +parser.add_argument('--dataset', required=True, help='skin') +parser.add_argument('--model', type=str, required=True, help='model file to use') +parser.add_argument('--input_nc', type=int, default=3, help='input image channels') +parser.add_argument('--output_nc', type=int, default=3, help='output image channels') +parser.add_argument('--ngf', type=int, default=64, help='generator filters in first conv layer') +parser.add_argument('--cuda', action='store_true', help='use cuda') +opt = parser.parse_args() +print(opt) +# opt.input_nc, opt.output_nc, opt.ngf +netG_state_dict = torch.load(opt.model) +netG = G(opt.input_nc, opt.output_nc, opt.ngf) +netG.load_state_dict(netG_state_dict) + +image_dir = ""dataset/{}/val_2018/"".format(opt.dataset) +image_filenames = [x for x in os.listdir(image_dir) if is_image_file(x)] + + +batchsize=2 +for image_name in image_filenames: + img, shape = load_img(image_dir + image_name) + + input_x_np = np.zeros((batchsize, 3, 128, 128)).astype(np.float32) + + input_x_np[0,:] = np.asarray(img[0]) + + input= Variable(torch.from_numpy(input_x_np)) + + if opt.cuda: + netG = netG.cuda() + input = input.cuda() + + out = netG(input) + + out = out.cpu() + out_img = out.data[0] + if not os.path.exists(""result""): + os.mkdir(""result"") + if not os.path.exists(os.path.join(""result"", opt.dataset)): + os.mkdir(os.path.join(""result"", opt.dataset)) + save_img(out_img, ""result/{}/128x128/2018/cGAN/{}"".format(opt.dataset, image_name), shape) +","Python" +"Multi-scale modeling","vivek231/Skin-Project","data.py",".py","287","16","from os.path import join + +from dataset import DatasetFromFolder + + +def get_training_set(root_dir): + train_dir = join(root_dir, ""train"") + + return DatasetFromFolder(train_dir) + + +def get_test_set(root_dir): + test_dir = join(root_dir, ""test"") + + return DatasetFromFolder(test_dir) +","Python" +"Multi-scale modeling","vivek231/Skin-Project","util.py",".py","2039","70","import torch +import torch.nn as nn +import torch.nn.functional as F +from enum import Enum +import cv2 +import numpy as np +from skimage import filters +from skimage.color import rgb2gray +from scipy.misc import imread, imresize, imsave, imshow +import png +from skimage.morphology import erosion, square, dilation +from skimage.filters import threshold_mean, threshold_otsu +from PIL import Image, ImageEnhance, ImageFilter +import torch.autograd.variable as Variable + +def is_image_file(filename): + return any(filename.endswith(extension) for extension in ["".png"", "".jpg"", "".jpeg""]) + +def load_img(filepath): + img = imread(filepath) + if len(img.shape) < 3: + img = np.expand_dims(img, axis=2) + img = np.repeat(img, 3, axis=2) + shape=img.shape + img = imresize(img, (128, 128)) + img = np.transpose(img, (2, 0, 1)) + img = torch.from_numpy(img) + img = preprocess_img(img) + return img, shape + +def save_img(img, filename, shape): + + img = deprocess_img(img) + img = img.numpy() + img *= 255 + img = img.clip(0, 255) + img = np.transpose(img, (1, 2, 0)) + img = imresize(img, (shape[0], shape[1], 1)) + img=rgb2gray(img) + thresh = threshold_otsu(img) + img= img > thresh + img = img.astype(np.uint8) + img=img*255 + imsave(filename, img) + print (""Image saved as {}"".format(filename)) + +def preprocess_img(img): + # [0,255] image to [0,1] + min = img.min().float() + max = img.max().float() + img = torch.FloatTensor(img.size()).copy_(img) + img.add_(-min).mul_(1.0 / (max - min)) + # RGB to BGR + idx = torch.LongTensor([2, 1, 0]) + img = torch.index_select(img, 0, idx) + # [0,1] to [-1,1] + img = img.mul_(2).add_(-1) + # check that input is in expected range + assert img.max() <= 1, 'badly scaled inputs' + assert img.min() >= -1, ""badly scaled inputs"" + return img + +def deprocess_img(img): + # BGR to RGB + idx = torch.LongTensor([2, 1, 0]) + img = torch.index_select(img, 0, idx) + # [-1,1] to [0,1] + img = img.add_(1).div_(2) + return img +","Python" +"Multi-scale modeling","mojtaba-komeili/ABAQUS-Subroutines","Subs.for",".for","20027","778","C ############################################################################################### +C +C AMPLITUDES +C +C ############################################################################################### + SUBROUTINE UAMP( + * ampName, time, ampValueOld, dt, nSvars, svars, + * lFlagsInfo, + * nSensor, sensorValues, sensorNames, jSensorLookUpTable, + * AmpValueNew, + * lFlagsDefine, + * AmpDerivative, AmpSecDerivative, AmpIncIntegral, + * AmpDoubleIntegral) +C + INCLUDE 'ABA_PARAM.INC' + +C time indices + parameter (iStepTime = 1, + * iTotalTime = 2, + * nTime = 2) +C flags passed in for information + parameter (iInitialization = 1, + * iRegularInc = 2, + * iCuts = 3, + * ikStep = 4, + * nFlagsInfo = 4) +C optional flags to be defined + parameter (iComputeDeriv = 1, + * iComputeSecDeriv = 2, + * iComputeInteg = 3, + * iComputeDoubleInteg = 4, + * iStopAnalysis = 5, + * iConcludeStep = 6, + * nFlagsDefine = 6) + dimension time(nTime), lFlagsInfo(nFlagsInfo), + * lFlagsDefine(nFlagsDefine) + dimension jSensorLookUpTable(*) + dimension sensorValues(nSensor), svars(nSvars) + character*80 sensorNames(nSensor) + character*80 ampName + + REAL*8 TOTAL_EPS_X1, TOTAL_EPS_X2, TOTAL_GAMMA + REAL*8 L, PI, RATIO, X1, X2 + REAL*8 GAMMA, EPS_X1, EPS_X2, VAL + INTEGER I, MODE + +C 1:Axial; 2:Shear; 3:Coupled + MODE = 1 + + PI= 2*DACOS(0.0D0) + L = 10.4D0 + + IF (MODE .EQ. 1) THEN ! Axial + TOTAL_EPS_X1 = 4.0D-2 + TOTAL_EPS_X2 = 4.0D-2 + TOTAL_GAMMA = 0 ! Degree + ELSEIF (MODE .EQ. 2) THEN ! Shear + TOTAL_EPS_X1 = 0.0D0 + TOTAL_EPS_X2 = 0.0D0 + TOTAL_GAMMA = 40 ! Degree + ELSE + TOTAL_EPS_X1 = 4.0D-2 + TOTAL_EPS_X2 = 4.0D-2 + TOTAL_GAMMA = 40 ! Degree + ENDIF + + EPS_X1 = time(iStepTime) * TOTAL_EPS_X1 + 1.0D-6 + EPS_X2 = time(iStepTime) * TOTAL_EPS_X2 + 1.0D-6 + GAMMA = time(iStepTime) * TOTAL_GAMMA * PI / 180 ! To radians + + IF (ampName .EQ. 'RP1-X1') THEN + CALL DEFORMATION_X1(L/2, L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + WRITE(*,*) ""TIME="", time(iStepTime), "" DTIME="", dt + + ELSEIF (ampName .EQ. 'RP1-X2') THEN + CALL DEFORMATION_X2(L/2, L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'RP2-X1') THEN + CALL DEFORMATION_X1(L/2, -L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'RP2-X2') THEN + CALL DEFORMATION_X2(L/2, -L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'RP3-X1') THEN + CALL DEFORMATION_X1(-L/2, L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'RP3-X2') THEN + CALL DEFORMATION_X2(-L/2, L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'RP4-X1') THEN + CALL DEFORMATION_X1(-L/2, -L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'RP4-X2') THEN + CALL DEFORMATION_X2(-L/2, -L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'XN-NODE-X1') THEN + CALL DEFORMATION_X1(-L/2, 0, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'XN-NODE-X2') THEN + CALL DEFORMATION_X2(-L/2, 0, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'YN-NODE-X1') THEN + CALL DEFORMATION_X1(0, -L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSEIF (ampName .EQ. 'YN-NODE-X2') THEN + CALL DEFORMATION_X2(0, -L/2, VAL, + 2 EPS_X1, EPS_X2, GAMMA) + AmpValueNew = VAL + + ELSE + WRITE (*,*) ""NO AMP!"" + WRITE (*,*) ampName + + END IF + + RETURN + END +C +C +C The defined functions for the deformation of the field +C +C + SUBROUTINE DEFORMATION_X1(X1_INIT,X2_INIT,X1_NEW,E1,E2,G) +C X1_NEW is the AmpValueNew + REAL*8 X1_INIT, X2_INIT, X1_NEW, E1, E2, G + + X1_NEW = X1_INIT*(1+E1)*DCOS(G/2) + X2_INIT*(1+E2)*DSIN(G/2) + 2 - X1_INIT + + END SUBROUTINE DEFORMATION_X1 + + + SUBROUTINE DEFORMATION_X2(X1_INIT,X2_INIT,X2_NEW,E1,E2,G) +C X2_NEW is the AmpValueNew + REAL*8 X1_INIT, X2_INIT, X2_NEW, E1, E2, G + + X2_NEW = X1_INIT*(1+E1)*DSIN(G/2) + X2_INIT*(1+E2)*DCOS(G/2) + 2 - X2_INIT + + END SUBROUTINE DEFORMATION_X2 + +C +C ############################################################################################### +C +C MPC (MULTI-POINT CONSTRAINTS) +C +C ############################################################################################### +C + SUBROUTINE MPC(UE,A,JDOF,MDOF,N,JTYPE,X,U,UINIT,MAXDOF, + * LMPC,KSTEP,KINC,TIME,NT,NF,TEMP,FIELD,LTRAN,TRAN) +C + INCLUDE 'ABA_PARAM.INC' +C + DIMENSION A(N),JDOF(N),X(6,N),U(MAXDOF,N),UINIT(MAXDOF,N), + * TIME(2),TEMP(NT,N),FIELD(NF,NT,N),LTRAN(N),TRAN(3,3,N) + + REAL*8 L, RATIO + INTEGER I + + L = 10.4 + +C ############################################## +C +C IF USED FOR X FACE SETS +C U3, NODE-3, xNzP; U4, NODE-1, xPzP +C U5, NODE-4, xNzN; U6, NODE-2, xPzN +C +C ############################################## +C +C IF USED FOR Z FACE SETS +C U3, NODE-1, xPzP; U4, NODE-2, xPzN +C U5, NODE-3, xNzP, U6, NODE-4, xNzN + IF (JTYPE .EQ. 1) THEN +C THE CONSTRAINT FOR DOF(1) + DO I = 1,N + JDOF(I) = 1 + END DO + ELSEIF (JTYPE .EQ. 2) THEN +C THE CONSTRAINT FOR DOF(2) + DO I = 1,N + JDOF(I) = 2 + END DO + ELSE + WRITE(*,*) ""ERROR!"" + END IF + + RATIO = SQRT((X(1,1)-X(1,3))**2 + (X(2,1)-X(2,3))**2)/L + + A(1) = 1 + A(2) = -1 + A(3) = -1 * (1-RATIO) + A(4) = -1 * RATIO + A(5) = 1 * (1-RATIO) + A(6) = 1 * RATIO + + RETURN + END + +C +C ############################################################################################### +C +C MATERIAL +C +C ############################################################################################### +C + SUBROUTINE UMAT(STRESS,STATEV,DDSDDE,SSE,SPD,SCD, + 1 RPL,DDSDDT,DRPLDE,DRPLDT, + 2 STRAN,DSTRAN,TIME,DTIME,TEMP,DTEMP,PREDEF,DPRED,CMNAME, + 3 NDI,NSHR,NTENS,NSTATV,PROPS,NPROPS,COORDS,DROT_2,PNEWDT, + 4 CELENT,DFGRD0,DFGRD1,NOEL,NPT,LAYER,KSPT,KSTEP,KINC) +C + INCLUDE 'ABA_PARAM.INC' +C + CHARACTER*80 CMNAME + DIMENSION STRESS(NTENS),STATEV(NSTATV), + 1 DDSDDE(NTENS,NTENS),DDSDDT(NTENS),DRPLDE(NTENS), + 2 STRAN(NTENS),DSTRAN(NTENS),TIME(2),PREDEF(1),DPRED(1), + 3 PROPS(NPROPS),COORDS(3),DROT_2(3,3),DFGRD0(3,3),DFGRD1(3,3) + +C + REAL*8 e0_1(3,1), e0_2(3,1), e0_3(3,1), eb1(3,1), eb2(3,1), eb3(3,1) + REAL*8 f1(3,1), f2(3,1), f3(3,1), f1v(3,1), f2v(3,1), f2b(1,1) + REAL*8 MAG_f1v, MAG_f2v, DUM(1,1) + REAL*8 THETA(3,3), R(3,3), F(3,3) + REAL*8 USQUARED(3,3), U(3,3), U_Inv(3,3), STATEV_VEC(6,1) + REAL*8 STRAIN_INC(6,1), NEW_STRESS(6,1), STRAIN_VEC(6,1) + REAL*8 STRAIN_VEC_F(6,1), NEW_STRESS_F(6,1), STRAIN_INC_F(6,1) + REAL*8 FABRIC_DDSDDE(6,6), M_MAT(6,6) + REAL*8 G, EComp, E, E0_lat, E0_22, E0_33, p + INTEGER ERR + + E = PROPS(2) + E0_22 = PROPS(3) + E0_33 = PROPS(4) + p = PROPS(5) + + E0_lat = 5.0D6 + EComp = E/20 + G = 25.0D6 * PROPS(6) ! PROPS(7) is The G factor in Isight + + F(1,1) = DBLE(DFGRD1(1,1)) + F(1,2) = DBLE(DFGRD1(1,2)) + F(1,3) = DBLE(DFGRD1(1,3)) + + F(2,1) = DBLE(DFGRD1(2,1)) + F(2,2) = DBLE(DFGRD1(2,2)) + F(2,3) = DBLE(DFGRD1(2,3)) + + F(3,1) = DBLE(DFGRD1(3,1)) + F(3,2) = DBLE(DFGRD1(3,2)) + F(3,3) = DBLE(DFGRD1(3,3)) + + USQUARED = MATMUL(TRANSPOSE(F),F) + + CALL MATSQRT(USQUARED,U) + + CALL FINDInv(U, U_Inv, 3, ERR) + + R = MATMUL(F, U_Inv) + + F = MATMUL(R,MATMUL(F,TRANSPOSE(R))) + + e0_1 = RESHAPE((/1, 0, 0/), (/3, 1/)) + e0_2 = RESHAPE((/0, 1, 0/), (/3, 1/)) + e0_3 = RESHAPE((/0, 0, 1/), (/3, 1/)) + + eb1= MATMUL(R, e0_1) + eb2= MATMUL(R, e0_2) + eb3= MATMUL(R, e0_3) + + f1v = MATMUL(F ,e0_1) + MAG_f1v = DSQRT(f1v(1,1)**2 + f1v(2,1)**2 + f1v(3,1)**2) + f1 = f1v / MAG_f1v + + f2b = MATMUL(TRANSPOSE(MATMUL(F ,e0_2)),f1) + f2v = MATMUL(F, e0_2) - f2b(1,1) * f1 + MAG_f2v = DSQRT(f2v(1,1)**2 + f2v(2,1)**2 + f2v(3,1)**2) + f2 = f2v / MAG_f2v + + CALL CROSSPRODUCT(f3, f1, f2) + + DUM = MATMUL(TRANSPOSE(f1),eb1) + THETA(1,1) = DUM(1,1) + DUM = MATMUL(TRANSPOSE(f1),eb2) + THETA(2,1) = DUM(1,1) + DUM = MATMUL(TRANSPOSE(f1),eb3) + THETA(3,1) = DUM(1,1) + + DUM = MATMUL(TRANSPOSE(f2),eb1) + THETA(1,2) = DUM(1,1) + DUM = MATMUL(TRANSPOSE(f2),eb2) + THETA(2,2) = DUM(1,1) + DUM = MATMUL(TRANSPOSE(f2),eb3) + THETA(3,2) = DUM(1,1) + + DUM = MATMUL(TRANSPOSE(f3),eb1) + THETA(1,3) = DUM(1,1) + DUM = MATMUL(TRANSPOSE(f3),eb2) + THETA(2,3) = DUM(1,1) + DUM = MATMUL(TRANSPOSE(f3),eb3) + THETA(3,3) = DUM(1,1) + + DO I = 1,6 + DO J = 1,6 + FABRIC_DDSDDE(I,J) = 0.0D0 + M_MAT(I,J) = 0.0D0 + END DO + END DO + + DO I=1,NSTATV + STATEV(I) = 0.0D0 + END DO + + DO I = 1,3 + NEW_STRESS(I,1) = DBLE(STRESS(I)) + STRAIN_INC(I,1) = DBLE(DSTRAN(I)) + STRAIN_VEC(I,1) = DBLE(STRAN(I)) + M_MAT(I,I) = 1.0D0 + J = I + 3 + NEW_STRESS(J,1) = DBLE(STRESS(J)) + STRAIN_INC(J,1) = DBLE(DSTRAN(J))/2 + STRAIN_VEC(J,1) = DBLE(STRAN(J))/2 + M_MAT(J,J) = 2.0D0 + END DO + + CALL ROTATE(STRAIN_VEC, STRAIN_VEC_F, THETA) + + STR = DABS(STRAIN_VEC_F(1,1)) + + IF (STRAIN_VEC_F(1,1) .GE. 0) THEN + FABRIC_DDSDDE(1,1) = E + ELSE + FABRIC_DDSDDE(1,1) = EComp + END IF + + G = G * (1 + STR * 1.0D3) + + FABRIC_DDSDDE(2,2) = E0_22 * STR * + 1 STRAIN_VEC_F(2,1)**2 * DABS(STRAIN_VEC_F(3,1)) + E0_lat + FABRIC_DDSDDE(3,3) = E0_33 * STR * + 1 STRAIN_VEC_F(2,1)**2 * DABS(STRAIN_VEC_F(3,1)) + E0_lat + + FABRIC_DDSDDE(4,4) = 2*G + FABRIC_DDSDDE(5,5) = 2*G + FABRIC_DDSDDE(6,6) = 2*G + + IF (PROPS(1) .EQ. 1.0) THEN ! TSM + CALL ROTATEC(FABRIC_DDSDDE,DDSDDE,THETA) + NEW_STRESS = NEW_STRESS + MATMUL(DDSDDE, + 1 MATMUL(M_MAT,STRAIN_INC)) + CALL ROTATE(NEW_STRESS, STATEV_VEC, THETA) + + ELSE IF (PROPS(1) .EQ. 2.0) THEN ! TSS + CALL ROTATEC(FABRIC_DDSDDE,DDSDDE,THETA) + CALL ROTATE(NEW_STRESS, NEW_STRESS_F, THETA) + CALL ROTATE(STRAIN_INC, STRAIN_INC_F, THETA) + + NEW_STRESS_F = NEW_STRESS_F + MATMUL(FABRIC_DDSDDE, + 1 MATMUL(M_MAT,STRAIN_INC_F)) + STATEV_VEC = NEW_STRESS_F + CALL ROTATE(NEW_STRESS_F, NEW_STRESS, TRANSPOSE(THETA)) + + ELSE IF (PROPS(1) .EQ. 3.0) THEN ! REGULAR STRESS UPDATE + DDSDDE = FABRIC_DDSDDE + NEW_STRESS = NEW_STRESS + MATMUL(FABRIC_DDSDDE, + 1 MATMUL(M_MAT,STRAIN_INC)) + STATEV_VEC = NEW_STRESS + END IF + + DO I = 1,6 + STATEV(I) = STATEV_VEC(I,1) + STRESS(I) = NEW_STRESS(I,1) + END DO + + STATEV(7) = G + STATEV(8) = FABRIC_DDSDDE(2,2) + STATEV(9) = FABRIC_DDSDDE(3,3) + + RETURN + END + +C ########################################################################### +C THE SUBROUTINES DEVELOPED OR MODIFIED BY MOJTABA +C +C THE SUBROUTINES WHICH ARE USED WITHOUT ANY CHANGES ARE ADDED +C IN THE INCLUDED FILE ""EISPACK_Functions.for"" + + SUBROUTINE FINDInv(matrix, inverse, n, errorflag) + !Subroutine to find the inverse of a square matrix + !Author : Louisda16th a.k.a Ashwith J. Rego + !Reference : Algorithm has been well explained in: + !http://math.uww.edu/~mcfarlat/inverse.htm + !http://www.tutor.ms.unimelb.edu.au/matrix/matrix_inverse.html + + INTEGER, INTENT(IN) :: n + INTEGER, INTENT(OUT) :: errorflag !Return -1 for error, 0 for normal + REAL*8, INTENT(IN), DIMENSION(n,n) :: matrix !Input matrix + REAL*8, INTENT(OUT), DIMENSION(n,n) :: inverse !Inverted matrix + + LOGICAL :: FLAG = .TRUE. + INTEGER :: i, j, k, l + REAL*8 m + REAL*8, DIMENSION(n,2*n) :: augmatrix !augmented matrix + + !Augment input matrix with an identity matrix + DO i = 1, n + DO j = 1, 2*n + IF (j <= n ) THEN + augmatrix(i,j) = matrix(i,j) + ELSE IF ((i+n) == j) THEN + augmatrix(i,j) = 1 + Else + augmatrix(i,j) = 0 + ENDIF + END DO + END DO + + !Reduce augmented matrix to upper traingular form + DO k =1, n-1 + IF (augmatrix(k,k) == 0) THEN + FLAG = .FALSE. + DO i = k+1, n + IF (augmatrix(i,k) /= 0) THEN + DO j = 1,2*n + augmatrix(k,j) = augmatrix(k,j)+augmatrix(i,j) + END DO + FLAG = .TRUE. + EXIT + ENDIF + IF (FLAG .EQV. .FALSE.) THEN + PRINT*, ""Matrix is non - invertible"" + inverse = 0 + errorflag = -1 + return + ENDIF + END DO + ENDIF + DO j = k+1, n + m = augmatrix(j,k)/augmatrix(k,k) + DO i = k, 2*n + augmatrix(j,i) = augmatrix(j,i) - m*augmatrix(k,i) + END DO + END DO + END DO + + !Test for invertibility + DO i = 1, n + IF (augmatrix(i,i) == 0) THEN + PRINT*, ""Matrix is non - invertible"" + inverse = 0 + errorflag = -1 + return + ENDIF + END DO + + !Make diagonal elements as 1 + DO i = 1 , n + m = augmatrix(i,i) + DO j = i , (2 * n) + augmatrix(i,j) = (augmatrix(i,j) / m) + END DO + END DO + + !Reduced right side half of augmented matrix to identity matrix + DO k = n-1, 1, -1 + DO i =1, k + m = augmatrix(i,k+1) + DO j = k, (2*n) + augmatrix(i,j) = augmatrix(i,j) -augmatrix(k+1,j) * m + END DO + END DO + END DO + + !store answer + DO i =1, n + DO j = 1, n + inverse(i,j) = augmatrix(i,j+n) + END DO + END DO + errorflag = 0 + END SUBROUTINE FINDinv + +C NORMALIZES A VECOTR (EIGENVECTOR) + + SUBROUTINE NORMALIZE(INP, OUT) + REAL*8 INP(3,1), OUT(3,1) + REAL*8 MAG + + MAG = DSQRT(INP(1,1)**2 + INP(2,1)**2 + INP(3,1)**2) + OUT = INP / MAG + + END SUBROUTINE NORMALIZE + + SUBROUTINE CROSSPRODUCT(ANS, A, B) + REAL*8 ANS(3,1), A(3,1), B(3,1) + + ANS(1,1) = A(2,1)*B(3,1) - A(3,1)*B(2,1) + ANS(2,1) =-(A(1,1)*B(3,1) - A(3,1)*B(1,1)) + ANS(3,1) = A(1,1)*B(2,1) - A(2,1)*B(1,1) + + END SUBROUTINE CROSSPRODUCT + +C SQUARE ROOT OF A MATRIX +C ///////////////////////////////////////////////////////// + SUBROUTINE MATSQRT(USQUARED, U) + REAL*8 USQUARED(3,3), TEMP_USQUARED(6), U(3,3), DIAGONALIZED(3,3) + REAL*8 EIGVAL(3), EIGVECS(3,3), TEMP(3) + REAL*8 EIGVEC1(3,1), EIGVEC2(3,1), EIGVEC3(3,1), Q(3,3) + INTEGER ERR, I + + TEMP_USQUARED(1) = USQUARED(1,1) + TEMP_USQUARED(2) = USQUARED(2,2) + TEMP_USQUARED(3) = USQUARED(3,3) + TEMP_USQUARED(4) = USQUARED(1,2) + TEMP_USQUARED(5) = USQUARED(1,3) + TEMP_USQUARED(6) = USQUARED(2,3) + + CALL SPRIND(TEMP_USQUARED, EIGVAL, EIGVECS, 1, 3, 3) + + DO I=1,3 + EIGVEC1(I,1) = EIGVECS(1,I) + EIGVEC2(I,1) = EIGVECS(2,I) + EIGVEC3(I,1) = EIGVECS(3,I) + END DO + + CALL NORMALIZE(EIGVEC1, EIGVEC1) + CALL NORMALIZE(EIGVEC2, EIGVEC2) + CALL NORMALIZE(EIGVEC3, EIGVEC3) + + + Q(1,1) = EIGVEC1(1,1) + Q(2,1) = EIGVEC1(2,1) + Q(3,1) = EIGVEC1(3,1) + + Q(1,2) = EIGVEC2(1,1) + Q(2,2) = EIGVEC2(2,1) + Q(3,2) = EIGVEC2(3,1) + + Q(1,3) = EIGVEC3(1,1) + Q(2,3) = EIGVEC3(2,1) + Q(3,3) = EIGVEC3(3,1) + + DIAGONALIZED = MATMUL(MATMUL(TRANSPOSE(Q),USQUARED),Q) + + DIAGONALIZED = DSQRT(DABS(DIAGONALIZED)) + + U = MATMUL(MATMUL(Q,DIAGONALIZED),TRANSPOSE(Q)) + + END SUBROUTINE MATSQRT + +C SUBROUTINE FOR ROTATING DDSDDE MATRIX +C ///////////////////////////////////////// + SUBROUTINE ROTATEC(C,C_PRIME, TH) + REAL*8 C(6,6), C_PRIME(6,6), T(6,6), TP(6,6), TH(3,3) + REAL*8 M(6,6), M_INV(6,6) + REAL*8 F11, F12, F13 + REAL*8 F21, F22, F23 + REAL*8 F31, F32, F33 + INTEGER I, J + + F11 = TH(1,1) + F12 = TH(2,1) + F13 = TH(3,1) + F21 = TH(1,2) + F22 = TH(2,2) + F23 = TH(3,2) + F31 = TH(1,3) + F32 = TH(2,3) + F33 = TH(3,3) + + DO I = 1,6 + DO J = 1,6 + C_PRIME(I,J) = 0.0D0 + M(I,J) = 0.0D0 + M_INV(I,J) = 0.0D0 + END DO + END DO + +C DEFINING T MATRIX + + T(1,1) = F11**2 + T(1,2) = F21**2 + T(1,3) = F31**2 + T(2,1) = F12**2 + T(2,2) = F22**2 + T(2,3) = F32**2 + T(3,1) = F13**2 + T(3,2) = F23**2 + T(3,3) = F33**2 + + T(1,4) = 2 * F11 * F21 + T(1,5) = 2 * F11 * F31 + T(1,6) = 2 * F31 * F21 + + T(2,4) = 2 * F12 * F22 + T(2,5) = 2 * F12 * F32 + T(2,6) = 2 * F32 * F22 + + T(3,4) = 2 * F13 * F23 + T(3,5) = 2 * F13 * F33 + T(3,6) = 2 * F33 * F23 + + T(4,1) = F11 * F12 + T(4,2) = F21 * F22 + T(4,3) = F31 * F32 + + T(5,1) = F11 * F13 + T(5,2) = F21 * F23 + T(5,3) = F31 * F33 + + T(6,1) = F12 * F13 + T(6,2) = F22 * F23 + T(6,3) = F32 * F33 + + T(4,4) = F12 * F21 + F11 * F22 + T(4,5) = F12 * F31 + F11 * F32 + T(4,6) = F22 * F31 + F21 * F32 + + T(5,4) = F13 * F21 + F11 * F23 + T(5,5) = F13 * F31 + F11 * F33 + T(5,6) = F23 * F31 + F21 * F33 + + T(6,4) = F13 * F22 + F12 * F23 + T(6,5) = F13 * F32 + F12 * F33 + T(6,6) = F23 * F32 + F22 * F33 + +C DEFINING THE T_PRIME MATRIX + + TP(1,1) = F11**2 + TP(1,2) = F12**2 + TP(1,3) = F13**2 + TP(2,1) = F21**2 + TP(2,2) = F22**2 + TP(2,3) = F23**2 + TP(3,1) = F31**2 + TP(3,2) = F32**2 + TP(3,3) = F33**2 + + TP(1,4) = 2 * F11 * F12 + TP(1,5) = 2 * F11 * F13 + TP(1,6) = 2 * F12 * F13 + + TP(2,4) = 2 * F21 * F22 + TP(2,5) = 2 * F21 * F23 + TP(2,6) = 2 * F22 * F23 + + TP(3,4) = 2 * F31 * F32 + TP(3,5) = 2 * F31 * F33 + TP(3,6) = 2 * F32 * F33 + + TP(4,1) = F11 * F21 + TP(4,2) = F12 * F22 + TP(4,3) = F13 * F23 + + TP(5,1) = F11 * F31 + TP(5,2) = F12 * F32 + TP(5,3) = F13 * F33 + + TP(6,1) = F21 * F31 + TP(6,2) = F22 * F32 + TP(6,3) = F23 * F33 + + TP(4,4) = F12 * F21 + F11 * F22 + TP(4,5) = F13 * F21 + F11 * F23 + TP(4,6) = F13 * F22 + F12 * F23 + + TP(5,4) = F12 * F31 + F11 * F32 + TP(5,5) = F13 * F31 + F11 * F33 + TP(5,6) = F13 * F32 + F12 * F33 + + TP(6,4) = F22 * F31 + F21 * F32 + TP(6,5) = F23 * F31 + F21 * F33 + TP(6,6) = F23 * F32 + F22 * F33 + + DO I = 1,3 + M(I,I) = 1.0D0 + M_INV(I,I) = 1.0D0 + J = I + 3 + M(J,J) = 2.0D0 + M_INV(J,J) = 0.5D0 + END DO + + C_PRIME = MATMUL(T,MATMUL(C,MATMUL(M,MATMUL(TP,M_INV)))) + + END SUBROUTINE ROTATEC + + + SUBROUTINE ROTATE(S,S_PRIME, TH) + REAL*8 S(6,1), S_PRIME(6,1), TP(6,6), TH(3,3) + REAL*8 F11, F12, F13 + REAL*8 F21, F22, F23 + REAL*8 F31, F32, F33 + INTEGER I, J + + F11 = TH(1,1) + F12 = TH(2,1) + F13 = TH(3,1) + F21 = TH(1,2) + F22 = TH(2,2) + F23 = TH(3,2) + F31 = TH(1,3) + F32 = TH(2,3) + F33 = TH(3,3) + + TP(1,1) = F11**2 + TP(1,2) = F12**2 + TP(1,3) = F13**2 + TP(2,1) = F21**2 + TP(2,2) = F22**2 + TP(2,3) = F23**2 + TP(3,1) = F31**2 + TP(3,2) = F32**2 + TP(3,3) = F33**2 + + TP(1,4) = 2 * F11 * F12 + TP(1,5) = 2 * F11 * F13 + TP(1,6) = 2 * F12 * F13 + + TP(2,4) = 2 * F21 * F22 + TP(2,5) = 2 * F21 * F23 + TP(2,6) = 2 * F22 * F23 + + TP(3,4) = 2 * F31 * F32 + TP(3,5) = 2 * F31 * F33 + TP(3,6) = 2 * F32 * F33 + + TP(4,1) = F11 * F21 + TP(4,2) = F12 * F22 + TP(4,3) = F13 * F23 + + TP(5,1) = F11 * F31 + TP(5,2) = F12 * F32 + TP(5,3) = F13 * F33 + + TP(6,1) = F21 * F31 + TP(6,2) = F22 * F32 + TP(6,3) = F23 * F33 + + TP(4,4) = F12 * F21 + F11 * F22 + TP(4,5) = F13 * F21 + F11 * F23 + TP(4,6) = F13 * F22 + F12 * F23 + + TP(5,4) = F12 * F31 + F11 * F32 + TP(5,5) = F13 * F31 + F11 * F33 + TP(5,6) = F13 * F32 + F12 * F33 + + TP(6,4) = F22 * F31 + F21 * F32 + TP(6,5) = F23 * F31 + F21 * F33 + TP(6,6) = F23 * F32 + F22 * F33 + + S_PRIME = MATMUL(TP,S) + + END SUBROUTINE ROTATE + +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","setup.py",".py","4464","122","import os +import re +import sys +import glob +import platform +import sysconfig +import subprocess + +from setuptools import setup, Extension +from setuptools.command.build_ext import build_ext +from setuptools.command.test import test +from distutils.version import LooseVersion + + +class CMakeExtension(Extension): + def __init__(self, name, sourcedir=''): + super(CMakeExtension, self).__init__(name, sources=[]) + self.sourcedir = os.path.abspath(sourcedir) + + +class CMakeBuild(build_ext): + user_options = [ + ('jobs=', 'j', 'Specify the number of build jobs at once'), + ] + + def initialize_options(self): + super().initialize_options() + self.jobs = None + + def finalize_options(self): + super().finalize_options() + assert self.jobs is None or self.jobs.isdecimal(), 'Invalid argument for --jobs or -j' + + def run(self): + try: + out = subprocess.check_output(['cmake', '--version']) + except OSError: + raise RuntimeError(""CMake must be installed to build the following extensions: "" + + "", "".join(e.name for e in self.extensions)) + + cmake_minimum_version_for_windows = '3.1.0' + if platform.system() == ""Windows"": + cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)', out.decode()).group(1)) + if cmake_version < cmake_minimum_version_for_windows: + raise RuntimeError(""CMake >= {} is required on Windows"".format( + cmake_minimum_version_for_windows)) + + for ext in self.extensions: + self.build_extension(ext) + + def build_extension(self, ext): + extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) + cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, + '-DPYTHON_EXECUTABLE=' + sys.executable] + + cfg = 'Debug' if self.debug else 'Release' + build_args = ['--config', cfg] + if self.jobs: + build_args += ['-j', self.jobs] + + if platform.system() == ""Windows"": + cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] + if sys.maxsize > 2**32: + cmake_args += ['-A', 'x64'] + build_args += ['--', '/m'] + cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] + + if platform.system() == ""Windows"": + env = os.environ.copy() + env['CXXFLAGS'] = '{} -DVERSION_INFO=\\""{}\\"" -I {}'.format( + env.get('CXXFLAGS', ''), + self.distribution.get_version(), + sysconfig.get_path('include')) + else: + env = os.environ.copy() + env['CXXFLAGS'] = '{} -DVERSION_INFO=\\""{}\\"" -isystem {}'.format( + env.get('CXXFLAGS', ''), + self.distribution.get_version(), + sysconfig.get_path('include')) + + if not os.path.exists(self.build_temp): + os.makedirs(self.build_temp) + subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) + subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp) + + +class CustomTestCommand(test): + def run(self): + super().run() + build_py = self.get_finalized_command('build_ext') + if platform.system() == ""Windows"": + subprocess.check_call(['ctest', '--output-on-failure', '--build-config', 'Release'], cwd=build_py.build_temp) + else: + subprocess.check_call(['ctest', '--output-on-failure'], cwd=build_py.build_temp) + + +DESCRIPTION = ( + ""A software platform for modeling, simulation and analysis of complex, "" + ""heterogeneous and multi-scale systems like the cell. E-Cell has "" + ""multi-algorithm, multi-timescale and multi-spatial-representation as "" + ""its central feature."" +) + +LONG_DESCRIPTION = open(""README.md"").read() + + +setup( + name='ecell4_base', + version = '2.1.2', + license = ""the GNU General Public License v2"", + author = ""Kazunari Kaizu"", + author_email = ""kaizu@riken.jp"", + url = ""https://github.com/ecell/ecell4_base"", + description = DESCRIPTION, + long_description = LONG_DESCRIPTION, + long_description_content_type='text/markdown', + data_files = [('ecell4-licenses', glob.glob('licenses/*'))], + ext_modules=[CMakeExtension('ecell4_base')], + cmdclass=dict(build_ext=CMakeBuild, test=CustomTestCommand), + zip_safe=False, +) +","Python" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/ODEFactory.hpp",".hpp","2257","103","#ifndef ECELL4_ODE_ODE_FACTORY2_HPP +#define ECELL4_ODE_ODE_FACTORY2_HPP + +#include +#include +#include + +#include ""ODEWorld.hpp"" +#include ""ODESimulator.hpp"" + + +namespace ecell4 +{ + +namespace ode +{ + +class ODEFactory: + public SimulatorFactory +{ +public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef ODEFactory this_type; + +public: + + ODEFactory(const ODESolverType solver_type = default_solver_type(), const Real dt = default_dt(), + const Real abs_tol = default_abs_tol(), const Real rel_tol = default_rel_tol()) + : base_type(), solver_type_(solver_type), dt_(dt), abs_tol_(abs_tol), rel_tol_(rel_tol) + { + ; // do nothing + } + + virtual ~ODEFactory() + { + ; // do nothing + } + + static inline const ODESolverType default_solver_type() + { + return ROSENBROCK4_CONTROLLER; + } + + static inline const Real default_dt() + { + return std::numeric_limits::infinity(); + } + + static inline const Real default_abs_tol() + { + return 0.0; + } + + static inline const Real default_rel_tol() + { + return 0.0; + } + + ODEFactory& rng(const std::shared_ptr& rng) + { + return (*this); //XXX: Just for the compatibility + } + + inline ODEFactory* rng_ptr(const std::shared_ptr& rng) + { + return &(this->rng(rng)); //XXX: == this + } + +protected: + + virtual simulator_type* create_simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const + { + simulator_type* sim = new simulator_type(w, m, solver_type_); + sim->set_dt(dt_); + + if (abs_tol_ > 0) + { + sim->set_absolute_tolerance(abs_tol_); + } + + if (rel_tol_ > 0) + { + sim->set_relative_tolerance(rel_tol_); + } + return sim; + } + +protected: + + ODESolverType solver_type_; + Real dt_, abs_tol_, rel_tol_; +}; + +} // ode + +} // ecell4 + +#endif /* ECELL4_ODE_ODE_FACTORY2_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/ODEWorld.cpp",".cpp","2184","79","#include ""ODEWorld.hpp"" +#include +#include +#include + +namespace ecell4 +{ + +namespace ode +{ + +void ODEWorld::bind_to(std::shared_ptr model) +{ + if (std::shared_ptr bound_model = lock_model()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to BDWorld"" + << std::endl; + } + } + + model_ = model; +} + +void ODEWorld::save(const std::string& filename) const +{ +#ifdef WITH_HDF5 + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + std::unique_ptr + group(new H5::Group(fout->createGroup(""CompartmentSpace""))); + save_compartment_space >(*this, group.get()); + + const uint32_t space_type = static_cast(Space::ELSE); + group->openAttribute(""type"").write(H5::PredType::STD_I32LE, &space_type); + + extras::save_version_information(fout.get(), std::string(""ecell4-ode-"") + std::string(VERSION_INFO)); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif +} + +void ODEWorld::load(const std::string& filename) +{ +#ifdef WITH_HDF5 + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-ode-0.0""; + try + { + const std::string version = extras::load_version_information(*fin); + if (!extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required << ""] or later is required.""; + throw NotSupported(ss.str()); + } + } + catch(H5::GroupIException not_found_error) + { + throw NotFound(""No version information was found.""); + } + + const H5::Group group(fin->openGroup(""CompartmentSpace"")); + load_compartment_space >(group, this); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif +} + +} // ode + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/ODEWorld.hpp",".hpp","9439","359","#ifndef ECELL4_ODE_ODE_WORLD_HPP +#define ECELL4_ODE_ODE_WORLD_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WITH_HDF5 +#include +#endif +#include + +namespace ecell4 +{ + +namespace ode +{ + +#ifdef WITH_HDF5 +template +struct ODEWorldHDF5Traits + : public CompartmentSpaceHDF5TraitsBase +{ + typedef CompartmentSpaceHDF5TraitsBase base_type; + typedef typename base_type::num_molecules_type num_molecules_type; + typedef typename base_type::space_type space_type; + + num_molecules_type getter(const space_type& space, const Species& sp) const + { + return space.get_value_exact(sp); + } + + void setter( + Tspace_& space, const Species& sp, const num_molecules_type& value) const + { + space.set_value(sp, value); + } +}; +#endif + +class ODEWorld + : public WorldInterface +{ +protected: + + typedef std::vector num_molecules_container_type; + typedef std::vector species_container_type; + typedef std::unordered_map< + Species, num_molecules_container_type::size_type> species_map_type; + +public: + + ODEWorld(const Real3& edge_lengths = Real3(1, 1, 1)) + : t_(0.0) + { + reset(edge_lengths); + } + + ODEWorld(const std::string& filename) + : t_(0.0) + { + reset(Real3(1, 1, 1)); + this->load(filename); + } + + // SpaceTraits + + const Real t() const + { + return t_; + } + + void set_t(const Real& t) + { + if (t < 0.0) + { + throw std::invalid_argument(""the time must be positive.""); + } + t_ = t; + } + + const Real3& edge_lengths() const + { + return edge_lengths_; + } + + void reset(const Real3& edge_lengths) + { + t_ = 0.0; + index_map_.clear(); + num_molecules_.clear(); + species_.clear(); + + for (Real3::size_type dim(0); dim < 3; ++dim) + { + if (edge_lengths[dim] <= 0) + { + throw std::invalid_argument(""the edge length must be positive.""); + } + } + + edge_lengths_ = edge_lengths; + volume_ = edge_lengths[0] * edge_lengths[1] * edge_lengths[2]; + } + + const Real volume() const + { + return volume_; + } + + void set_volume(const Real& volume) + { + if (volume <= 0.0) + { + throw std::invalid_argument(""The volume must be positive.""); + } + + volume_ = volume; + const Real L(cbrt(volume)); + edge_lengths_ = Real3(L, L, L); + } + + Integer num_molecules(const Species& sp) const + { + return static_cast(get_value(sp)); + } + + Integer num_molecules_exact(const Species& sp) const + { + return static_cast(get_value_exact(sp)); + } + + std::vector list_species() const + { + return species_; + } + + void add_molecules(const Species& sp, const Real& num) + { + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + reserve_species(sp); + i = index_map_.find(sp); + } + + num_molecules_[(*i).second] += num; + } + + void remove_molecules(const Species& sp, const Real& num) + { + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + throw NotFound(""Species not found""); + } + + num_molecules_[(*i).second] -= num; + } + + Real get_value(const Species& sp) const + { + SpeciesExpressionMatcher sexp(sp); + Real retval(0); + for (species_map_type::const_iterator i(index_map_.begin()); + i != index_map_.end(); ++i) + { + retval += num_molecules_[(*i).second] * sexp.count((*i).first); + } + return retval; + } + + Real get_value_exact(const Species& sp) const + { + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + // throw NotFound(""Species not found""); + return 0.0; + } + + return num_molecules_[(*i).second]; + } + + void set_value(const Species& sp, const Real& num) + { + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + reserve_species(sp); + i = index_map_.find(sp); + } + + num_molecules_[(*i).second] = num; + } + + void save(const std::string& filename) const; + void load(const std::string& filename); + + bool has_species(const Species& sp) const + { + species_map_type::const_iterator i(index_map_.find(sp)); + return (i != index_map_.end()); + } + + void reserve_species(const Species& sp) + { + species_map_type::const_iterator i(index_map_.find(sp)); + if (i != index_map_.end()) + { + throw AlreadyExists(""Species already exists""); + } + + index_map_.insert(std::make_pair(sp, num_molecules_.size())); + species_.push_back(sp); + num_molecules_.push_back(0); + } + + void release_species(const Species& sp) + { + species_map_type::iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + throw NotFound(""Species not found""); + } + + species_map_type::mapped_type + idx((*i).second), last_idx(num_molecules_.size() - 1); + if (idx != last_idx) + { + const species_container_type::size_type + idx_(static_cast(idx)), + last_idx_( + static_cast(last_idx)); + const Species& last_sp(species_[last_idx_]); + species_[idx_] = last_sp; + num_molecules_[idx] = num_molecules_[last_idx]; + index_map_[last_sp] = idx; + } + + species_.pop_back(); + num_molecules_.pop_back(); + index_map_.erase(sp); + } + + void bind_to(std::shared_ptr model); + + std::shared_ptr lock_model() const + { + return model_.lock(); + } + + void add_molecules(const Species& sp, const Integer& num, + const std::shared_ptr shape) + { + add_molecules(sp, num); + } + + std::pair, bool> new_particle(const Particle& p) + { + add_molecules(p.species(), 1); + return std::make_pair(std::make_pair(ParticleID(), p), true); + } + + std::pair, bool> new_particle( + const Species& sp, const Real3& pos) + { + add_molecules(sp, 1); + return std::make_pair( + std::make_pair(ParticleID(), Particle(sp, pos, 0.0, 0.0)), true); + } + + std::vector get_values() const + { + return num_molecules_; + } + + Real evaluate(const ReactionRule& rr) const + { + if (rr.has_descriptor()) + { + const std::shared_ptr desc = rr.get_descriptor(); + return __evaluate(rr, desc); + } + else + { + const std::shared_ptr + rrd(new ReactionRuleDescriptorMassAction(rr.k())); + rrd->resize_reactants(rr.reactants().size()); + rrd->resize_products(rr.products().size()); + return __evaluate(rr, rrd); + } + } + + std::vector evaluate(const std::vector& reaction_rules) const + { + std::vector ret(reaction_rules.size(), 0.0); + unsigned i = 0; + for(std::vector::const_iterator + it(reaction_rules.begin()); it != reaction_rules.end(); it++, i++) + { + ret[i] = this->evaluate(*it); + } + return ret; + } + +protected: + + Real __evaluate(const ReactionRule& rr, const std::shared_ptr& desc) const + { + const ReactionRule::reactant_container_type reactants = rr.reactants(); + const ReactionRule::product_container_type products = rr.products(); + + ReactionRuleDescriptor::state_container_type::size_type cnt(0); + + ReactionRuleDescriptor::state_container_type r(reactants.size()); + for(ReactionRule::reactant_container_type::const_iterator j(reactants.begin()); + j != reactants.end(); j++, cnt++) + { + r[cnt] = static_cast(this->get_value_exact(*j)); + } + + cnt = 0; + + ReactionRuleDescriptor::state_container_type p(products.size()); + for(ReactionRule::reactant_container_type::const_iterator j(products.begin()); + j != products.end(); j++, cnt++) + { + p[cnt] = static_cast(this->get_value_exact(*j)); + } + + return desc->propensity(r, p, this->volume(), this->t()); + } + +protected: + + Real3 edge_lengths_; + Real volume_; + Real t_; + + num_molecules_container_type num_molecules_; + species_container_type species_; + species_map_type index_map_; + + std::weak_ptr model_; +}; + +} // ode + +} // ecell4 + +#endif /* ECELL4_ODE_ODE_WORLD_NEW_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/ODESimulator.hpp",".hpp","29883","744","#ifndef ECELL4_ODE_ODE_SIMULATOR_NEW_HPP +#define ECELL4_ODE_ODE_SIMULATOR_NEW_HPP + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include + +#include ""ODEWorld.hpp"" + +namespace ecell4 +{ +namespace ode +{ + +enum ODESolverType { + RUNGE_KUTTA_CASH_KARP54 = 0, + ROSENBROCK4_CONTROLLER = 1, + EULER = 2, +}; + +class ODESimulator + : public SimulatorBase +{ +public: + + typedef SimulatorBase base_type; + +public: + + typedef boost::numeric::ublas::vector state_type; + typedef boost::numeric::ublas::matrix matrix_type; + typedef std::vector index_container_type; + typedef std::vector coefficient_container_type; + + struct reaction_type + { + index_container_type reactants; + coefficient_container_type reactant_coefficients; + index_container_type products; + coefficient_container_type product_coefficients; + Real k; + // std::weak_ptr ratelaw; + // const ODEReactionRule *raw; + std::weak_ptr ratelaw; + }; + typedef std::vector reaction_container_type; + + class deriv_func + { + public: + deriv_func(const reaction_container_type &reactions, const Real &volume) + : reactions_(reactions), volume_(volume), vinv_(1.0 / volume) + { + ; + } + + void operator()(const state_type &x, state_type &dxdt, const double &t) + { + std::fill(dxdt.begin(), dxdt.end(), 0.0); + for(reaction_container_type::const_iterator i(reactions_.begin()); + i != reactions_.end(); i++) + { + ReactionRuleDescriptor::state_container_type reactants_states(i->reactants.size()); + ReactionRuleDescriptor::state_container_type products_states(i->products.size()); + ReactionRuleDescriptor::state_container_type::size_type cnt(0); + + for(index_container_type::const_iterator j(i->reactants.begin()); + j != i->reactants.end(); j++, cnt++) + { + reactants_states[cnt] = x[*j]; + } + cnt = 0; + for(index_container_type::const_iterator j(i->products.begin()); + j != i->products.end(); j++, cnt++) + { + products_states[cnt] = x[*j]; + } + double flux; + // Calculation! XXX + if (i->ratelaw.expired()) + { + std::unique_ptr temporary_ratelaw_obj(new ReactionRuleDescriptorMassAction(i->k, i->reactant_coefficients, i->product_coefficients)); + flux = temporary_ratelaw_obj->propensity(reactants_states, products_states, volume_, t); + } + else + { + std::shared_ptr ratelaw = i->ratelaw.lock(); + assert(ratelaw->is_available()); + flux = ratelaw->propensity(reactants_states, products_states, volume_, t); + } + // Merge each reaction's flux into whole dxdt + std::size_t nth = 0; + for(index_container_type::const_iterator j(i->reactants.begin()); + j != i->reactants.end(); j++) + { + dxdt[*j] -= (flux * (double)i->reactant_coefficients[nth]); + nth++; + } + nth = 0; + for(index_container_type::const_iterator j(i->products.begin()); + j != i->products.end(); j++) + { + dxdt[*j] += (flux * (double)i->product_coefficients[nth]); + nth++; + } + } + return; + } + protected: + const reaction_container_type reactions_; + const Real volume_; + const Real vinv_; + }; + + class jacobi_func + { + public: + jacobi_func( + const reaction_container_type &reactions, const Real& volume, + const Real& abs_tol, const Real& rel_tol) + : reactions_(reactions), volume_(volume), vinv_(1.0 / volume), abs_tol_(abs_tol), rel_tol_(rel_tol) + { + ; + } + void operator()( + const state_type& x, matrix_type& jacobi, const double &t, state_type &dfdt) const + { + //fill 0 into jacobi and dfdt + std::fill(dfdt.begin(), dfdt.end(), 0.0); + std::fill(jacobi.data().begin(), jacobi.data().end(), 0.0); + + // const Real ETA(2.2204460492503131e-16); + const Real SQRTETA(1.4901161193847656e-08); + const Real r0(1.0); + // Real fac(0.0); + // for (std::size_t k(0); k < dfdt.size(); ++k) + // { + // const Real ewtk(atol + rtol * x[k]); + // fac = std::max(fac, dfdt[k] * ewtk); + // } + // const Real r0(1000.0 * h * ETA * dfdt.size() * fac); //XXX: h means the step interval + // { + // const Real ewtj(atol + rtol * x[j]); + // const Real dyj(std::max(SQRTETA * abs(x[j]), r0 * ewtj)); + // } + + // const Real h(1.0e-8); + // const Real ht(1.0e-10); + const Real ht(1.0e-10); + + // calculate jacobian for each reaction and merge it. + for(reaction_container_type::const_iterator i(reactions_.begin()); + i != reactions_.end(); i++) + { + // Calculate one reactions's jabobian + // Prepare the state_array to pass ReactionRuleDescriptor. + index_container_type::size_type reactants_size(i->reactants.size()); + index_container_type::size_type products_size(i->products.size()); + ReactionRuleDescriptor::state_container_type reactants_states(reactants_size); + ReactionRuleDescriptor::state_container_type products_states(products_size); + ReactionRuleDescriptor::state_container_type::size_type cnt(0); + for(index_container_type::const_iterator j(i->reactants.begin()); + j != i->reactants.end(); j++, cnt++) + { + reactants_states[cnt] = x[*j]; + } + cnt = 0; + for(index_container_type::const_iterator j(i->products.begin()); + j != i->products.end(); j++, cnt++) + { + products_states[cnt] = x[*j]; + } + // Call the ReactionRuleDescriptor object + + if (i->ratelaw.expired()) + { + std::unique_ptr temporary_ratelaw_obj(new ReactionRuleDescriptorMassAction(i->k, i->reactant_coefficients, i->product_coefficients)); + Real flux_0 = temporary_ratelaw_obj->propensity(reactants_states, products_states, volume_, t); + // Differentiate by time + { + Real flux = temporary_ratelaw_obj->propensity(reactants_states, products_states, volume_, t + ht); + Real flux_deriv = (flux - flux_0) / ht; + if (flux_deriv != 0.0) + { + for(std::size_t k(0); k < i->reactants.size(); k++) + { + matrix_type::size_type row = i->reactants[k]; + Real coeff = i->reactant_coefficients[k]; + dfdt[row] -= coeff * flux_deriv; + } + for(std::size_t k(0); k < i->products.size(); k++) + { + matrix_type::size_type row = i->products[k]; + Real coeff = i->product_coefficients[k]; + dfdt[row] += coeff * flux_deriv; + } + } + } + // Differentiate by each Reactants + for(std::size_t j(0); j < reactants_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(reactants_states[j]); + const Real h = std::max(SQRTETA * abs(reactants_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(reactants_states); + h_shift[j] += h; + Real flux = temporary_ratelaw_obj->propensity(h_shift, products_states, volume_, t); + Real flux_deriv = (flux - flux_0) / h; + matrix_type::size_type col = i->reactants[j]; + for(std::size_t k(0); k < i->reactants.size(); k++) + { + matrix_type::size_type row = i->reactants[k]; + Real coeff = i->reactant_coefficients[k]; + jacobi(row, col) -= coeff * flux_deriv; + } + for(std::size_t k(0); k < i->products.size(); k++) + { + matrix_type::size_type row = i->products[k]; + Real coeff = i->product_coefficients[k]; + jacobi(row, col) += coeff * flux_deriv; + } + } + // Differentiate by Products + for(std::size_t j(0); j < products_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(products_states[j]); + const Real h = std::max(SQRTETA * abs(products_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(products_states); + h_shift[j] += h; + Real flux = temporary_ratelaw_obj->propensity(reactants_states, h_shift, volume_, t); + Real flux_deriv = (flux - flux_0) / h; + matrix_type::size_type col = i->products[j]; + for(std::size_t k(0); k < i->reactants.size(); k++) + { + matrix_type::size_type row = i->reactants[k]; + Real coeff = i->reactant_coefficients[k]; + jacobi(row, col) -= coeff * flux_deriv; + } + for(std::size_t k(0); k < i->products.size(); k++) + { + matrix_type::size_type row = i->products[k]; + Real coeff = i->product_coefficients[k]; + jacobi(row, col) += coeff * flux_deriv; + } + } + } + else + { + std::shared_ptr ratelaw = i->ratelaw.lock(); + assert(ratelaw->is_available()); + Real flux_0 = ratelaw->propensity(reactants_states, products_states, volume_, t); + // Differentiate by time + { + Real flux = ratelaw->propensity(reactants_states, products_states, volume_, t + ht); + Real flux_deriv = (flux - flux_0) / ht; + if (flux_deriv != 0.0) + { + for(std::size_t k(0); k < i->reactants.size(); k++) + { + matrix_type::size_type row = i->reactants[k]; + Real coeff = i->reactant_coefficients[k]; + dfdt[row] -= coeff * flux_deriv; + } + for(std::size_t k(0); k < i->products.size(); k++) + { + matrix_type::size_type row = i->products[k]; + Real coeff = i->product_coefficients[k]; + dfdt[row] += coeff * flux_deriv; + } + } + } + // Differentiate by each Reactants + for(std::size_t j(0); j < reactants_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(reactants_states[j]); + const Real h = std::max(SQRTETA * abs(reactants_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(reactants_states); + h_shift[j] += h; + Real flux = ratelaw->propensity(h_shift, products_states, volume_, t); + Real flux_deriv = (flux - flux_0) / h; + matrix_type::size_type col = i->reactants[j]; + for(std::size_t k(0); k < i->reactants.size(); k++) + { + matrix_type::size_type row = i->reactants[k]; + Real coeff = i->reactant_coefficients[k]; + jacobi(row, col) -= coeff * flux_deriv; + } + for(std::size_t k(0); k < i->products.size(); k++) + { + matrix_type::size_type row = i->products[k]; + Real coeff = i->product_coefficients[k]; + jacobi(row, col) += coeff * flux_deriv; + } + } + // Differentiate by Products + for(std::size_t j(0); j < products_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(products_states[j]); + const Real h = std::max(SQRTETA * abs(products_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(products_states); + h_shift[j] += h; + Real flux = ratelaw->propensity(reactants_states, h_shift, volume_, t); + Real flux_deriv = (flux - flux_0) / h; + matrix_type::size_type col = i->products[j]; + for(std::size_t k(0); k < i->reactants.size(); k++) + { + matrix_type::size_type row = i->reactants[k]; + Real coeff = i->reactant_coefficients[k]; + jacobi(row, col) -= coeff * flux_deriv; + } + for(std::size_t k(0); k < i->products.size(); k++) + { + matrix_type::size_type row = i->products[k]; + Real coeff = i->product_coefficients[k]; + jacobi(row, col) += coeff * flux_deriv; + } + } + } + } + } + protected: + const reaction_container_type reactions_; + const Real volume_; + const Real vinv_; + const Real abs_tol_, rel_tol_; + }; + + class elasticity_func + { + public: + elasticity_func( + const reaction_container_type &reactions, const Real& volume, + const Real& abs_tol, const Real& rel_tol) + : reactions_(reactions), volume_(volume), vinv_(1.0 / volume), abs_tol_(abs_tol), rel_tol_(rel_tol) + { + ; + } + void operator()( + const state_type& x, matrix_type& elasticity, const double &t) const + { + //fill 0 into elasticity + std::fill(elasticity.data().begin(), elasticity.data().end(), 0.0); + + // const Real ETA(2.2204460492503131e-16); + const Real SQRTETA(1.4901161193847656e-08); + const Real r0(1.0); + // Real fac(0.0); + // for (std::size_t k(0); k < dfdt.size(); ++k) + // { + // const Real ewtk(atol + rtol * x[k]); + // fac = std::max(fac, dfdt[k] * ewtk); + // } + // const Real r0(1000.0 * h * ETA * dfdt.size() * fac); //XXX: h means the step interval + // { + // const Real ewtj(atol + rtol * x[j]); + // const Real dyj(std::max(SQRTETA * abs(x[j]), r0 * ewtj)); + // } + + // const Real h(1.0e-8); + // const Real ht(1.0e-10); + const Real ht(1.0e-10); + + // calculate elasticityan for each reaction and merge it. + unsigned reaction_idx = 0; + for(reaction_container_type::const_iterator i(reactions_.begin()); + i != reactions_.end(); i++, reaction_idx++) + { + // Calculate one reactions's jabobian + // Prepare the state_array to pass ReactionRuleDescriptor. + index_container_type::size_type reactants_size(i->reactants.size()); + index_container_type::size_type products_size(i->products.size()); + ReactionRuleDescriptor::state_container_type reactants_states(reactants_size); + ReactionRuleDescriptor::state_container_type products_states(products_size); + ReactionRuleDescriptor::state_container_type::size_type cnt(0); + for(index_container_type::const_iterator j(i->reactants.begin()); + j != i->reactants.end(); j++, cnt++) + { + reactants_states[cnt] = x[*j]; + } + cnt = 0; + for(index_container_type::const_iterator j(i->products.begin()); + j != i->products.end(); j++, cnt++) + { + products_states[cnt] = x[*j]; + } + // Call the ReactionRuleDescriptor object + + if (i->ratelaw.expired()) + { + std::unique_ptr temporary_ratelaw_obj(new ReactionRuleDescriptorMassAction(i->k, i->reactant_coefficients, i->product_coefficients)); + Real flux_0 = temporary_ratelaw_obj->propensity(reactants_states, products_states, volume_, t); + // Differentiate by each Reactants + for(std::size_t j(0); j < reactants_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(reactants_states[j]); + const Real h = std::max(SQRTETA * abs(reactants_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(reactants_states); + h_shift[j] += h; + const Real flux = temporary_ratelaw_obj->propensity(h_shift, products_states, volume_, t); + const Real flux_deriv = (flux - flux_0) / h; + const matrix_type::size_type row = reaction_idx; + const matrix_type::size_type col = i->reactants[j]; + elasticity(row, col) = flux_deriv; + } + // Differentiate by Products + for(std::size_t j(0); j < products_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(products_states[j]); + const Real h = std::max(SQRTETA * abs(products_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(products_states); + h_shift[j] += h; + const Real flux = temporary_ratelaw_obj->propensity(reactants_states, h_shift, volume_, t); + const Real flux_deriv = (flux - flux_0) / h; + const matrix_type::size_type row = reaction_idx; + const matrix_type::size_type col = i->products[j]; + elasticity(row, col) = flux_deriv; + } + } + else + { + std::shared_ptr ratelaw = i->ratelaw.lock(); + assert(ratelaw->is_available()); + Real flux_0 = ratelaw->propensity(reactants_states, products_states, volume_, t); + // Differentiate by each Reactants + for(std::size_t j(0); j < reactants_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(reactants_states[j]); + const Real h = std::max(SQRTETA * abs(reactants_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(reactants_states); + h_shift[j] += h; + const Real flux = ratelaw->propensity(h_shift, products_states, volume_, t); + const Real flux_deriv = (flux - flux_0) / h; + const matrix_type::size_type row = reaction_idx; + const matrix_type::size_type col = i->reactants[j]; + elasticity(row, col) += flux_deriv; + } + // Differentiate by Products + for(std::size_t j(0); j < products_states.size(); j++) + { + const Real ewt = abs_tol_ + rel_tol_ * abs(products_states[j]); + const Real h = std::max(SQRTETA * abs(products_states[j]), r0 * ewt); + ReactionRuleDescriptor::state_container_type h_shift(products_states); + h_shift[j] += h; + const Real flux = ratelaw->propensity(reactants_states, h_shift, volume_, t); + const Real flux_deriv = (flux - flux_0) / h; + const matrix_type::size_type row = reaction_idx; + const matrix_type::size_type col = i->products[j]; + elasticity(row, col) += flux_deriv; + } + } + } + } + + protected: + + const reaction_container_type reactions_; + const Real volume_; + const Real vinv_; + const Real abs_tol_, rel_tol_; + }; + + struct StateAndTimeBackInserter + { + typedef std::vector state_container_type; + typedef std::vector time_container_type; + + state_container_type &m_states; + time_container_type &m_times; + StateAndTimeBackInserter( + state_container_type &states, time_container_type ×) + : m_states(states), m_times(times) + { + ; + } + void operator()(const state_type &x, double t) + { + m_states.push_back(x); + m_times.push_back(t); + } + }; +public: + + ODESimulator( + const std::shared_ptr& world, + const std::shared_ptr& model, + const ODESolverType solver_type = ROSENBROCK4_CONTROLLER) + : base_type(world, model), dt_(std::numeric_limits::infinity()), + abs_tol_(1e-6), rel_tol_(1e-6), max_dt_(0.0), solver_type_(solver_type) + { + initialize(); + } + + ODESimulator( + const std::shared_ptr& world, + const ODESolverType solver_type = ROSENBROCK4_CONTROLLER) + : base_type(world), dt_(std::numeric_limits::infinity()), + abs_tol_(1e-6), rel_tol_(1e-6), max_dt_(0.0), solver_type_(solver_type) + { + initialize(); + } + + void initialize() + { + if (!model_->is_static()) + { + throw std::runtime_error(""Only a NetworkModel is accepted. Use expand""); + } + const std::vector species(model_->list_species()); + for(std::vector::const_iterator it = species.begin(); + it != species.end(); it++) + { + if (!(world_->has_species(*it))) + { + world_->reserve_species(*it); + } + } + + // ode_reaction_rules_ = convert_ode_reaction_rules(model_); + } + + void step(void) + { + step(next_time()); + } + + bool step(const Real &upto); + + // Real next_time() const + // { + // return this->t() + this->dt(); + // } + // SimulatorTraits + + Real t(void) const + { + return world_->t(); + } + + void set_t(const Real &t) + { + world_->set_t(t); + } + + Real dt(void) const + { + return this->dt_; + } + + void set_dt(const Real &dt) + { + if (dt <= 0) + { + throw std::invalid_argument(""The step size must be positive.""); + } + dt_ = dt; + } + // Integer num_steps() const + // { + // return this->num_steps_; + // } + // + + Real absolute_tolerance() const + { + return abs_tol_; + } + + void set_absolute_tolerance(const Real abs_tol) + { + if (abs_tol < 0) + { + throw std::invalid_argument(""A tolerance must be positive or zero.""); + } + abs_tol_ = abs_tol; + } + + Real relative_tolerance() const + { + return rel_tol_; + } + + void set_relative_tolerance(const Real rel_tol) + { + if (rel_tol < 0) + { + throw std::invalid_argument(""A tolerance must be positive or zero.""); + } + rel_tol_ = rel_tol; + } + + Real maximum_step_interval() const + { + return max_dt_; + } + + void set_maximum_step_interval(const Real max_dt) + { + if (max_dt < 0) + { + throw std::invalid_argument(""A maximum step interval must be positive or zero.""); + } + max_dt_ = max_dt; + } + + std::vector derivatives() const + { + const std::vector species_list(world_->list_species()); + const unsigned n = species_list.size(); + + state_type x(n); + { + state_type::size_type i(0); + for(Model::species_container_type::const_iterator it(species_list.begin()); + it != species_list.end(); it++, i++) + { + x[i] = static_cast(world_->get_value_exact(*it)); + } + } + + state_type dxdt(n); + + std::pair system(generate_system()); + system.first(x, dxdt, world_->t()); + + std::vector ret(dxdt.size()); + std::copy(dxdt.begin(), dxdt.end(), ret.begin()); + return ret; + } + + std::vector > jacobian() const + { + const std::vector species_list(world_->list_species()); + const unsigned n = species_list.size(); + + state_type x(n); + { + state_type::size_type i(0); + for(Model::species_container_type::const_iterator it(species_list.begin()); + it != species_list.end(); it++, i++) + { + x[i] = static_cast(world_->get_value_exact(*it)); + } + } + + matrix_type jacobi(n, n); + state_type dfdt(n); + + std::pair system(generate_system()); + system.second(x, jacobi, world_->t(), dfdt); + + std::vector > ret(jacobi.size1()); + for (unsigned i = 0; i != jacobi.size1(); i++) + { + ret[i].resize(jacobi.size2()); + for (unsigned j = 0; j != jacobi.size2(); j++) + { + ret[i][j] = jacobi(i, j); + } + } + return ret; + } + + std::vector values() const + { + return world_->get_values(); + } + + std::vector fluxes() const + { + return world_->evaluate(model_->reaction_rules()); + } + + std::vector > stoichiometry() const + { + return extras::get_stoichiometry(world_->list_species(), model_->reaction_rules()); + } + + std::vector > elasticity() const + { + const std::vector species_list(world_->list_species()); + const std::vector& reaction_rules(model_->reaction_rules()); + const unsigned n = species_list.size(); + const unsigned m = reaction_rules.size(); + + state_type x(n); + { + state_type::size_type i(0); + for(Model::species_container_type::const_iterator it(species_list.begin()); + it != species_list.end(); it++, i++) + { + x[i] = static_cast(world_->get_value_exact(*it)); + } + } + + matrix_type elas(m, n); + + const reaction_container_type reactions(convert_reactions()); + elasticity_func(reactions, world_->volume(), abs_tol_, rel_tol_)(x, elas, world_->t()); + + std::vector > ret(elas.size1()); + for (unsigned i = 0; i != elas.size1(); i++) + { + ret[i].resize(elas.size2()); + for (unsigned j = 0; j != elas.size2(); j++) + { + ret[i][j] = elas(i, j); + } + } + return ret; + } + +protected: + + reaction_container_type convert_reactions() const; + std::pair generate_system() const; + +protected: + + // std::shared_ptr model_; + // std::shared_ptr world_; + Real dt_; + // Integer num_steps_; + Real abs_tol_, rel_tol_, max_dt_; + ODESolverType solver_type_; + + // ODENetworkModel::ode_reaction_rule_container_type ode_reaction_rules_; +}; + +} // ode + +} // ecell4 + +#endif // ECELL4_ODE_ODE_SIMULATOR2_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/ODESimulator.cpp",".cpp","5738","173","#include ""ODESimulator.hpp"" + +#include +#include + +namespace odeint = boost::numeric::odeint; + +namespace ecell4 +{ + +namespace ode +{ + +ODESimulator::reaction_container_type ODESimulator::convert_reactions() const +{ + const std::vector species(world_->list_species()); + const Model::reaction_rule_container_type& reaction_rules = model_->reaction_rules(); + typedef std::unordered_map< + Species, state_type::size_type> species_map_type; + + species_map_type index_map; + state_type::size_type i(0); + for(std::vector::const_iterator it(species.begin()); + it != species.end(); it++) + { + index_map[*it] = i; + i++; + } + + std::vector reactions; + reactions.reserve(reaction_rules.size()); + for(Model::reaction_rule_container_type::const_iterator + i(reaction_rules.begin()); i != reaction_rules.end(); i++) + { + const ReactionRule& rr = (*i); + + const ReactionRule::reactant_container_type reactants(rr.reactants()); + const ReactionRule::product_container_type products(rr.products()); + + reaction_type r; + + r.k = rr.k(); + + r.reactants.reserve(reactants.size()); + for(ReactionRule::reactant_container_type::const_iterator j(reactants.begin()); + j != reactants.end(); j++) + { + r.reactants.push_back(index_map[*j]); + } + + r.products.reserve(products.size()); + for(ReactionRule::product_container_type::const_iterator j(products.begin()); + j != products.end(); j++) + { + r.products.push_back(index_map[*j]); + } + + if (rr.has_descriptor() && rr.get_descriptor()->has_coefficients()) + { + const std::shared_ptr& rrd(rr.get_descriptor()); + + r.ratelaw = rr.get_descriptor(); + + const ReactionRuleDescriptor::coefficient_container_type& reactants_coeff = rrd->reactant_coefficients(); + std::copy(reactants_coeff.begin(), reactants_coeff.end(), std::back_inserter(r.reactant_coefficients)); + + const ReactionRuleDescriptor::coefficient_container_type& products_coeff = rrd->product_coefficients(); + std::copy(products_coeff.begin(), products_coeff.end(), std::back_inserter(r.product_coefficients)); + } + else + { + r.reactant_coefficients.resize(reactants.size(), 1.0); + r.product_coefficients.resize(products.size(), 1.0); + } + + reactions.push_back(r); + } + return reactions; +} + +std::pair +ODESimulator::generate_system() const +{ + const reaction_container_type reactions(convert_reactions()); + return std::make_pair( + deriv_func(reactions, world_->volume()), + jacobi_func(reactions, world_->volume(), abs_tol_, rel_tol_)); +} + +bool ODESimulator::step(const Real &upto) +{ + if (upto <= t()) + { + return false; + } + const Real dt(std::min(dt_, upto - t())); + + const Real ntime(std::min(upto, t() + dt_)); + + //initialize(); + const std::vector species(world_->list_species()); + + state_type x(species.size()); + state_type::size_type i(0); + for(Model::species_container_type::const_iterator it(species.begin()); + it != species.end(); it++) + { + x[i] = static_cast(world_->get_value_exact(*it)); + i++; + } + std::pair system(generate_system()); + StateAndTimeBackInserter::state_container_type x_vec; + StateAndTimeBackInserter::time_container_type times; + + size_t steps; + switch (this->solver_type_) { + case ecell4::ode::RUNGE_KUTTA_CASH_KARP54: + { + /* This solver doesn't need the jacobian */ + typedef odeint::runge_kutta_cash_karp54 error_stepper_type; + steps = ( + odeint::integrate_adaptive( + odeint::make_controlled(abs_tol_, rel_tol_, max_dt_), + system.first, x, t(), ntime, dt, + StateAndTimeBackInserter(x_vec, times))); + } + break; + case ecell4::ode::ROSENBROCK4_CONTROLLER: + { + typedef odeint::rosenbrock4 error_stepper_type; + steps = ( + odeint::integrate_adaptive( + odeint::make_controlled(abs_tol_, rel_tol_, max_dt_), + system, x, t(), ntime, dt, + StateAndTimeBackInserter(x_vec, times))); + } + break; + case ecell4::ode::EULER: + { + typedef odeint::euler stepper_type; + steps = ( + odeint::integrate_const( + stepper_type(), system.first, x, t(), ntime, dt, + StateAndTimeBackInserter(x_vec, times))); + } + break; + default: + throw IllegalState(""Solver is not specified\n""); + }; + + // const double a_x(1.0), a_dxdt(1.0); + // const size_t steps( + // odeint::integrate_adaptive( + // controlled_stepper, system, x, t(), upto, dt_, + // StateAndTimeBackInserter(x_vec, times))); + { + state_type::size_type i(0); + for(Model::species_container_type::const_iterator + it(species.begin()); it != species.end(); it++) + { + world_->set_value(*it, static_cast(x_vec[steps](i))); + i++; + } + } + set_t(ntime); + num_steps_++; + return (ntime < upto); +} + +} // ode + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/samples/dissociation.cpp",".cpp","1582","61","#include + +#include +#include +#include +#include + +//#include + +using namespace ecell4; +using namespace ecell4::ode; + +/** + * main function + */ +int main(int argc, char** argv) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + ReactionRule rr1; + rr1.set_k(1.0); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + model->add_reaction_rule(rr1); + + std::shared_ptr world(new ODEWorld(edge_lengths)); + world->add_molecules(sp1, 60); + world->save(""test_ode.h5""); + + world->bind_to(model); + + ODESimulator target(world, model); + target.initialize(); + + Real next_time(0.0), dt(0.01); + + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + for (unsigned int i(0); i < 200; ++i) + { + next_time += dt; + target.step(next_time); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/samples/run_test.cpp",".cpp","6603","185","#include + +#include +#include +#include +#include + +#include +#include +#include + +#include + + +using namespace ecell4; +using namespace ecell4::ode; + +bool floatcmp(Real a, Real b, Real tol = 1e-12) +{ + return (fabs(a - b) <= tol); +} + +/** + * main function + */ +int test(int type, int use_coefficients = 0) +{ + // type: + // 1: RUNGE_KUTTA + // 2: ROSENBLOCK + // 3: EULER + // method: + // 0: only mass action + // 1: use user-defined function. + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real volume(L * L * L); + const Real N(60); + const Real U(0.5); + const Real ka(use_coefficients == 0 ? 0.1 : 0.1 / (N * U / volume)); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + ReactionRule rr1, rr2; + rr1.set_k(ka); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + + const Real kd(use_coefficients == 0 ? ka * volume * (1 - U) / (U * U * N) : ka * 4); + rr2.set_k(kd); + rr2.add_reactant(sp2); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + + // ReactionRule rr3; + // rr3.add_reactant(sp1); + // rr3.add_product(sp3); + + ODEReactionRule ode_rr1(rr1); + ODEReactionRule ode_rr2(rr2); + // ODEReactionRule ode_rr3(rr3); + + std::cout << rr1.as_string() << std::endl; + if (use_coefficients == 1) { + ode_rr1.set_reactant_coefficient(0, 2.0); + ode_rr2.set_product_coefficient(0, 2.0); + //ode_rr1.set_product_coefficient(0, 2.0); + //ode_rr3.set_product_coefficient(0, 2.0); + + std::shared_ptr rrd1(new ReactionRuleDescriptorMassAction(rr1.k())); + rrd1->set_reactant_coefficient(0, 2.0); + rrd1->set_product_coefficient(1, 1.0); + rr1.set_descriptor(rrd1); + std::shared_ptr rrd2(new ReactionRuleDescriptorMassAction(rr2.k())); + rrd2->set_reactant_coefficient(1, 1.0); + rrd2->set_product_coefficient(0, 2.0); + rr2.set_descriptor(rrd2); + } + std::cout << rr1.as_string() << std::endl; + // Setup NetworkModel + std::shared_ptr new_model(new NetworkModel()); + // new_model->add_species_attribute(sp1); + // new_model->add_species_attribute(sp2); + // new_model->add_species_attribute(sp3); + new_model->add_reaction_rule(rr1); + new_model->add_reaction_rule(rr2); + // new_model->add_reaction_rule(rr3); + + // Setup ODENetworkModel + std::shared_ptr ode_model(new ODENetworkModel); + // ode_model->add_species_attribute(sp1); + // ode_model->add_species_attribute(sp2); + // ode_model->add_species_attribute(sp3); + ode_model->add_reaction_rule(ode_rr1); + ode_model->add_reaction_rule(ode_rr2); + // ode_model->add_reaction_rule(ode_rr3); + ode_model->dump_reactions(); + + std::shared_ptr world(new ODEWorld(edge_lengths)); + std::shared_ptr new_world(new ODEWorld_New(edge_lengths)); + + world->add_molecules(sp1, N); + new_world->add_molecules(sp1, N); + + //ODESimulator target(model, world, RUNGE_KUTTA_CASH_KARP54); + ODESolverType soltype; + switch (type) { + case 1: + soltype = RUNGE_KUTTA_CASH_KARP54; + break; + case 2: + soltype = ROSENBROCK4_CONTROLLER; + break; + case 3: + soltype = EULER; + break; + default: + throw; + } + + ODESimulator target(ode_model, world, soltype); + target.initialize(); + + //ODESimulator_New new_target(model, new_world, RUNGE_KUTTA_CASH_KARP54); + ODESimulator_New new_target(new_model, new_world, soltype); + // ODESimulator_New new_target(ode_model, new_world, soltype); + new_target.initialize(); + + Real next_time(0.0), dt(0.01); + std::cout << boost::format(""%6s %6s %6s %6s %6s %6s %6s %s"") % ""time"" % ""A_old"" % ""B_old"" % ""C_old"" % ""A_new"" % ""B_new"" % ""C_new"" % ""BOOL"" << std::endl; + std::cout << boost::format(""%6.f %6d %6d %6d %6d %6d %6d %s"") % + target.t() % + world->num_molecules(sp1) % world->num_molecules(sp2) % world->num_molecules(sp3) % + new_world->num_molecules(sp1) % new_world->num_molecules(sp2) % new_world->num_molecules(sp3) % + ( world->num_molecules(sp1) == new_world->num_molecules(sp1) && + world->num_molecules(sp2) == new_world->num_molecules(sp2) && + world->num_molecules(sp3) == new_world->num_molecules(sp3) ) ; + + //std::cout << target.t() + // << ""\t"" << world->num_molecules(sp1) + // << ""\t"" << world->num_molecules(sp2) + // << ""\t"" << world->num_molecules(sp3) + // << std::endl; + + bool ok_flag = true; + for (unsigned int i(0); i < 1000; ++i) + { + next_time += dt; + target.step(next_time); + new_target.step(next_time); + if (target.t() != new_target.t() ) { + throw; + } + //std::cout << target.t() + // << ""\t"" << world->num_molecules(sp1) + // << ""\t"" << world->num_molecules(sp2) + // << ""\t"" << world->num_molecules(sp3) + // << std::endl; + bool flag = floatcmp(world->get_value(sp1), new_world->get_value(sp1)) && floatcmp(world->get_value(sp2), new_world->get_value(sp2)) && floatcmp(world->get_value(sp3), new_world->get_value(sp3)); + // bool flag = (world->num_molecules(sp1) == new_world->num_molecules(sp1)) && ( world->num_molecules(sp2) == new_world->num_molecules(sp2) ) && ( world->num_molecules(sp3) == new_world->num_molecules(sp3) ); + std::cout << boost::format(""%8.2f %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f %s\n"") % + target.t() % + world->get_value(sp1) % world->get_value(sp2) % world->get_value(sp3) % + new_world->get_value(sp1) % new_world->get_value(sp2) % new_world->get_value(sp3) % (flag == true ? ""TRUE"" : ""FALSE"" ); + if (flag != true) { + ok_flag = false; + } + } + std::cout << world->evaluate(ode_rr1) << "" "" << new_world->evaluate(rr1) << std::endl; + std::cout << world->evaluate(ode_rr2) << "" "" << new_world->evaluate(rr2) << std::endl; + if (ok_flag) { + std::cout << ""Exactly the same result with new and old ODESimulator"" << std::endl; + } + return ok_flag; +} + +int main(int argc, char** argv) +{ + test(1,0); + test(2,1); + //test(3,0); + //test(3,1); + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/samples/equilibrium.cpp",".cpp","1790","65","#include + +#include +#include +#include +#include + + +using namespace ecell4; +using namespace ecell4::ode; + +/** + * main function + */ +int main(int argc, char** argv) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real volume(L * L * L); + const Real N(60); + const Real ka(0.1), U(0.5); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + ReactionRule rr1, rr2; + rr1.set_k(ka); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + const Real kd(ka * volume * (1 - U) / (U * U * N)); + rr2.set_k(kd); + rr2.add_reactant(sp2); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + model->add_reaction_rule(rr1); + model->add_reaction_rule(rr2); + + std::shared_ptr world(new ODEWorld(edge_lengths)); + world->add_molecules(sp1, N); + + ODESimulator target(world, model, ROSENBROCK4_CONTROLLER); + target.initialize(); + + Real next_time(0.0), dt(0.01); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + for (unsigned int i(0); i < 1000; ++i) + { + next_time += dt; + target.step(next_time); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/samples/equilibrium2.cpp",".cpp","2010","72","#include + +#include +#include +#include +#include + +using namespace ecell4; +using namespace ecell4::ode; + +/** + * main function + */ +int main(int argc, char** argv) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real volume(L * L * L); + const Real N(60); + const Real ka(0.1), U(0.5); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + ReactionRule rr1, rr2; + rr1.set_k(ka); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + + const Real kd(ka * volume * (1 - U) / (U * U * N)); + rr2.set_k(kd); + rr2.add_reactant(sp2); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + model->add_reaction_rule(rr1); + model->add_reaction_rule(rr2); + + // std::shared_ptr ode_model(new ODENetworkModel(model) ); + // ReactionRule rr3; + // rr3.add_reactant(sp1); + // rr3.add_product(sp3); + // ode_model->add_reaction_rule(rr3); + // ode_model->dump_reactions(); + + std::shared_ptr world(new ODEWorld(edge_lengths)); + world->add_molecules(sp1, N); + + ODESimulator target(world, model); + target.initialize(); + + Real next_time(0.0), dt(0.01); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + for (unsigned int i(0); i < 1000; ++i) + { + next_time += dt; + target.step(next_time); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/samples/odesimulator2.cpp",".cpp","2710","84"," +#include + +#include +#include +#include +// #include +// #include +// #include +#include +#include + + +using namespace ecell4; +using namespace ecell4::ode; + +double f(ReactionRuleDescriptor::state_container_type const &reac, ReactionRuleDescriptor::state_container_type const &prod, double const v, double const time, ReactionRuleDescriptorCPPfunc const &rr) +{ + return 0.0; +} + +int main(int argc, char **argv) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real volume(L * L * L); + const Real N(60); + const Real ka(0.1), U(0.5); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + ReactionRule rr1, rr2; + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + std::shared_ptr ratelaw1(new ReactionRuleDescriptorMassAction(ka)); + ratelaw1->resize_reactants(1); + ratelaw1->resize_products(2); + rr1.set_descriptor(ratelaw1); + std::cout << ratelaw1->k() << std::endl; + + const Real kd(ka * volume * (1 - U) / (U * U * N)); + rr2.add_reactant(sp2); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + std::shared_ptr ratelaw2(new ReactionRuleDescriptorMassAction(kd)); + ratelaw2->resize_reactants(2); + ratelaw2->resize_products(1); + rr2.set_descriptor(ratelaw2); + // std::cout << ratelaw2->k() << std::endl; + + std::shared_ptr model(new NetworkModel()); + model->add_reaction_rule(rr1); + model->add_reaction_rule(rr2); + + for (Model::reaction_rule_container_type::const_iterator i(model->reaction_rules().begin()); + i != model->reaction_rules().end(); ++i) + { + std::cout << (*i).as_string() << std::endl; + } + + std::shared_ptr world(new ODEWorld(edge_lengths)); + world->add_molecules(sp1, N); + + ODESimulator sim(world, model, ROSENBROCK4_CONTROLLER); + sim.initialize(); + Real next_time(0.0), dt(0.01); + std::cout << sim.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + for(unsigned int i(0); i < 100000; i++) + { + next_time += dt; + sim.step(next_time); + std::cout << sim.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + } + return 0; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/samples/equilibrium_new.cpp",".cpp","4540","137","#include + +#include +#include +#include +#include + + +using namespace ecell4; +using namespace ecell4::ode; + +const bool use_coeff = true; + +// Real mass_action(const ReactionRuleDescriptor::state_container_type& r, const ReactionRuleDescriptor::state_container_type& p, Real volume, Real t, const ReactionRuleDescriptorCPPfunc& rd) +// { +// Real ret = volume; +// // Real ret = k_ * volume; +// ReactionRuleDescriptor::state_container_type::const_iterator i(r.begin()); +// ReactionRuleDescriptor::reaction_coefficient_list_type::const_iterator j(rd.reactant_coefficients().begin()); +// for (; i != r.end() && j != rd.reactant_coefficients().end(); ++i, ++j) +// { +// ret *= std::pow((*i) / volume, (*j)); +// } +// return ret; +// } + +/** + * main function + */ +int main(int argc, char** argv) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real volume(L * L * L); + const Real N(100); + const Real U(0.5); + const Real ka(use_coeff == 0 ? 0.1 : 0.1 / (N * U / volume)); + const Real kd(use_coeff == 0 ? ka * volume * (1 - U) / (U * U * N) : ka * std::pow((2 * U / (1 - U)), 2)); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + + ReactionRule rr1; + rr1.set_k(ka); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + + if (use_coeff) + { + // std::shared_ptr rr1_desc(new ReactionRuleDescriptorCPPfunc(mass_action)); + std::shared_ptr rr1_desc(new ReactionRuleDescriptorMassAction(rr1.k())); + std::vector rr1_left; + std::vector rr1_right; + rr1_left.push_back(2.0); + rr1_right.push_back(1.0); + rr1_right.push_back(1.0); + rr1_desc->set_reactant_coefficients(rr1_left); + rr1_desc->set_product_coefficients(rr1_right); + rr1_desc->resize_reactants(1); + rr1_desc->resize_products(2); + rr1.set_descriptor(rr1_desc); + + assert(rr1.has_descriptor()); + } + + ReactionRule rr2; + rr2.set_k(kd); + rr2.add_reactant(sp2); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + + if (use_coeff) + { + // std::shared_ptr rr2_desc(new ReactionRuleDescriptorCPPfunc(mass_action)); + std::shared_ptr rr2_desc(new ReactionRuleDescriptorMassAction(rr2.k())); + std::vector rr2_left; + std::vector rr2_right; + rr2_left.push_back(1.0); + rr2_left.push_back(1.0); + rr2_right.push_back(2.0); + rr2_desc->set_reactant_coefficients(rr2_left); + rr2_desc->set_product_coefficients(rr2_right); + rr2_desc->resize_reactants(2); + rr2_desc->resize_products(1); + rr2.set_descriptor(rr2_desc); + } + + std::shared_ptr model(new NetworkModel()); + model->add_reaction_rule(rr1); + model->add_reaction_rule(rr2); + + // ReactionRule rr3; + // rr3.add_reactant(sp1); + // rr3.add_product(sp3); + + //if (use_coeff) { + // std::shared_ptr rr3_desc(new ReactionRuleDescriptorCPPfunc(NULL) ); + // std::vector rr3_left; + // std::vector rr3_right; + // rr3_left.push_back(2.0); + // rr3_right.push_back(2.0); + // rr3_desc->set_reactant_coefficients(rr3_left); + // rr3_desc->set_product_coefficients(rr3_right); + // rr3.set_descriptor(rr3_desc); + //} + + // model->add_reaction_rule(rr3); + + // model->dump_reactions(); + + std::shared_ptr world(new ODEWorld(edge_lengths)); + world->add_molecules(sp1, N); + + ODESimulator target(world, model, RUNGE_KUTTA_CASH_KARP54); + target.initialize(); + + std::cout << world->evaluate(model->reaction_rules()[0]) << std::endl; + std::cout << world->evaluate(model->reaction_rules()[1]) << std::endl; + + Real next_time(0.0), dt(1.0); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + for (unsigned int i(0); i < 100; ++i) + { + next_time += dt; + target.step(next_time); + std::cout << target.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/tests/ODESimulator_test.cpp",".cpp","2009","74","#define BOOST_TEST_MODULE ""ODESimulator_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include +#include ""../ODESimulator.hpp"" + +using namespace ecell4; +using namespace ecell4::ode; + + +BOOST_AUTO_TEST_CASE(ODESimulator_test_constructor) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + + std::shared_ptr model(new NetworkModel()); + std::shared_ptr world(new ODEWorld(edge_lengths)); + + ODESimulator target(world, model); +} + +BOOST_AUTO_TEST_CASE(ODESimulator_test_step1) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + + std::shared_ptr model(new NetworkModel()); + std::shared_ptr world(new ODEWorld(edge_lengths)); + + ODESimulator target(world, model); + // target.step(1.0); //XXX: why not? +} + +BOOST_AUTO_TEST_CASE(ODESimulator_test_step2) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + ReactionRule rr1; + rr1.set_k(1.0); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.add_product(sp3); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + model->add_reaction_rule(rr1); + + std::shared_ptr world(new ODEWorld(edge_lengths)); + world->reserve_species(sp1); + world->set_value(sp1, 60); + + ODESimulator target(world, model); + + // std::cout << target.t() << "":"" << world->num_molecules(sp1) + // << "":"" << world->num_molecules(sp2) << std::endl; + target.step(1.0); + // std::cout << target.t() << "":"" << world->num_molecules(sp1) + // << "":"" << world->num_molecules(sp2) << std::endl; + + // BOOST_ASSERT(false); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/ode/tests/ODESimulator_new_test.cpp",".cpp","2549","88","#define BOOST_TEST_MODULE ""ODESimulator_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include +#include ""../ODESimulator_New.hpp"" + + +using namespace ecell4; +using namespace ecell4::ode; + +BOOST_AUTO_TEST_CASE(ODESimulator_test_constructor) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + ODEWorld_New world(edge_lengths); + BOOST_CHECK_EQUAL(world.t(), 0.); + + world.set_t(0.5); + BOOST_CHECK_EQUAL(world.t(), 0.5); + + BOOST_CHECK_EQUAL(world.edge_lengths() , edge_lengths); + BOOST_CHECK_EQUAL(world.volume(), edge_lengths[0] * edge_lengths[1] * edge_lengths[2]); + + // Compartment Space related + Species sp1(""A""); + Species sp2(""B""); + Species sp3(""C""); + world.add_molecules(sp1, 5.00); + world.add_molecules(sp2, 10.00); + world.add_molecules(sp3, 0.00); + + BOOST_CHECK_EQUAL(world.get_value(sp1), 5.0); + BOOST_CHECK_EQUAL(world.get_value(sp2),10.0); + BOOST_CHECK_EQUAL(world.get_value(sp3), 0.0); + + BOOST_CHECK_EQUAL(world.get_value_exact(sp1), 5.0); + BOOST_CHECK_EQUAL(world.get_value_exact(sp2),10.0); + BOOST_CHECK_EQUAL(world.get_value_exact(sp3), 0.0); + + BOOST_CHECK_EQUAL(world.has_species(sp1), true); + BOOST_CHECK_EQUAL(world.has_species(Species(""B"")), true); + BOOST_CHECK_EQUAL(world.has_species(Species(""D"")),false); +} + +BOOST_AUTO_TEST_CASE(ODESimulator_test_ClasicRR) +{ + // Without ReactionDescriptor. + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + std::shared_ptr world(new ODEWorld_New(edge_lengths)); + + ReactionRule rr1; + Species sp1(""A""), sp2(""B""); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + rr1.set_k(1.0); + + Real sp1_initial_value = 100.; + world->add_molecules(sp1, sp1_initial_value); + + std::shared_ptr new_model(new NetworkModel()); + { + new_model->add_species_attribute(sp1); + new_model->add_species_attribute(sp2); + new_model->add_reaction_rule(rr1); + } + + ODESolverType type = RUNGE_KUTTA_CASH_KARP54; + ODESimulator_New target(world, new_model, type); + + Real dt = 0.1; + target.set_dt(dt); + + BOOST_CHECK_EQUAL(target.t(), 0.); + BOOST_CHECK_EQUAL(target.dt(), dt); + + BOOST_TEST(target.step(10) ); // must return true + BOOST_TEST(world->get_value_exact(sp1) < sp1_initial_value); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/MesoscopicSimulator.cpp",".cpp","9616","345","#include +#include +#include + +#include +#include +#include +#include + +#include ""MesoscopicSimulator.hpp"" + + +namespace ecell4 +{ + +namespace meso +{ + +void MesoscopicSimulator::increment(const std::shared_ptr& pool, const coordinate_type& c) +{ + pool->add_molecules(1, c); + + for (boost::ptr_vector::iterator i(proxies_.begin()); + i != proxies_.end(); ++i) + { + (*i).inc(pool->species(), c); + } +} + +void MesoscopicSimulator::decrement(const std::shared_ptr& pool, const coordinate_type& c) +{ + pool->remove_molecules(1, c); + + for (boost::ptr_vector::iterator i(proxies_.begin()); + i != proxies_.end(); ++i) + { + (*i).dec(pool->species(), c); + } +} + +void MesoscopicSimulator::increment_molecules(const Species& sp, const coordinate_type& c) +{ + if (!world_->has_species(sp)) + { + if (world_->has_structure(sp)) + { + return; // do nothing + } + + const std::shared_ptr pool = world_->reserve_pool(sp); + proxies_.push_back(create_diffusion_proxy(sp)); + increment(pool, c); + } + else + { + increment(world_->get_pool(sp), c); + } +} + +void MesoscopicSimulator::decrement_molecules(const Species& sp, const coordinate_type& c) +{ + if (world_->has_species(sp)) + { + decrement(world_->get_pool(sp), c); + } + else + { + assert(world_->has_structure(sp)); // do nothing + } +} + +std::pair +MesoscopicSimulator::draw_next_reaction(const coordinate_type& c) +{ + constexpr Real inf = std::numeric_limits::infinity(); + std::vector a(proxies_.size()); + for (unsigned int idx(0); idx < proxies_.size(); ++idx) + { + a[idx] = proxies_[idx].propensity(c); + } + + const double atot(std::accumulate(a.begin(), a.end(), double(0.0))); + if (atot == 0.0) + { + return std::make_pair(inf, (ReactionRuleProxyBase*)NULL); + } + + if (atot == inf) + { + std::vector selected; + for (unsigned int i(0); i < a.size(); ++i) + { + if (a[i] == inf) + { + selected.push_back(i); + } + } + + const unsigned int idx = selected[(selected.size() == 1 ? 0 : rng()->uniform_int(0, selected.size() - 1))]; + return std::make_pair(0.0, &proxies_[idx]); + } + + const double rnd1(rng()->uniform(0, 1)); + const double dt(gsl_sf_log(1.0 / rnd1) / double(atot)); + const double rnd2(rng()->uniform(0, atot)); + + int u(-1); + double acc(0.0); + const int len_a(a.size()); + do + { + u++; + acc += a[u]; + } while (acc < rnd2 && u < len_a - 1); + + if (len_a == u) + { + return std::make_pair(inf, (ReactionRuleProxyBase*)NULL); + } + + return std::make_pair(dt, &proxies_[u]); +} + +void MesoscopicSimulator::interrupt_all(const Real& t) +{ + EventScheduler::events_range events(scheduler_.events()); + for (EventScheduler::events_range::iterator itr(events.begin()); + itr != events.end(); ++itr) + { + (*itr).second->interrupt(t); + scheduler_.update(*itr); + } +} + +void MesoscopicSimulator::step(void) +{ + if (this->dt() == std::numeric_limits::infinity()) + { + // Any reactions cannot occur. + return; + } + + interrupted_ = event_ids_.size(); + EventScheduler::value_type const& top(scheduler_.top()); + const Real tnext(top.second->time()); + top.second->fire(); // top.second->time_ is updated in fire() + this->set_t(tnext); + scheduler_.update(top); + + if (interrupted_ < static_cast(event_ids_.size())) + { + EventScheduler::identifier_type evid(event_ids_[interrupted_]); + std::shared_ptr ev(scheduler_.get(evid)); + ev->interrupt(t()); + scheduler_.update(std::make_pair(evid, ev)); + } + + // EventScheduler::value_type top(scheduler_.pop()); + // const Real tnext(top.second->time()); + // top.second->fire(); // top.second->time_ is updated in fire() + // this->set_t(tnext); + // // EventScheduler::events_range events(scheduler_.events()); + // // for (EventScheduler::events_range::iterator itr(events.begin()); + // // itr != events.end(); ++itr) + // // { + // // (*itr).second->interrupt(tnext); + // // scheduler_.update(*itr); + // // } + // scheduler_.add(top.second); + + num_steps_++; +} + +bool MesoscopicSimulator::step(const Real &upto) +{ + if (upto <= t()) + { + return false; + } + + if (upto >= next_time()) + { + step(); + return true; + } + else + { + // nothing happens + // set_dt(next_time() - upto); + set_t(upto); + last_reactions_.clear(); + // interrupt_all(upto); //XXX: Is this really needed? + return false; + } +} + +MesoscopicSimulator::DiffusionProxy* +MesoscopicSimulator::create_diffusion_proxy(const Species& sp) +{ + DiffusionProxy* proxy = new DiffusionProxy(this, sp); + proxy->initialize(); + for (boost::ptr_vector::size_type i = 0; + i < diffusion_proxy_offset_; ++i) + { + proxy->set_dependency( + dynamic_cast(&proxies_[i])); + } + return proxy; +} + +void MesoscopicSimulator::check_model(void) +{ + const Model::reaction_rule_container_type& + reaction_rules(model_->reaction_rules()); + + for (Model::reaction_rule_container_type::const_iterator + i(reaction_rules.begin()); i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + + if (rr.has_descriptor()) + { + const std::shared_ptr& desc = rr.get_descriptor(); + + if (!desc->is_available()) + { + throw NotSupported( + ""The given reaction rule descriptor is not available.""); + } + else if ((rr.reactants().size() != desc->reactant_coefficients().size()) + || (rr.products().size() != desc->product_coefficients().size())) + { + throw NotSupported( + ""Mismatch between the number of stoichiometry coefficients and of reactants.""); + } + else + { + for (ReactionRuleDescriptor::coefficient_container_type::const_iterator + it(desc->reactant_coefficients().begin()); it != desc->reactant_coefficients().end(); + it++) + { + if ((*it) < 0) + { + throw NotSupported(""A stoichiometric coefficient must be non-negative.""); + } + else if (abs((*it) - round(*it)) > 1e-10 * (*it)) + { + throw NotSupported(""A stoichiometric coefficient must be an integer.""); + } + } + } + } + else if (rr.reactants().size() > 2) + { + throw NotSupported(""No more than 2 reactants are supported.""); + } + } +} + +void MesoscopicSimulator::initialize(void) +{ + const Model::reaction_rule_container_type& + reaction_rules(model_->reaction_rules()); + + check_model(); + + proxies_.clear(); + for (Model::reaction_rule_container_type::const_iterator + i(reaction_rules.begin()); i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + + if (rr.has_descriptor()) + { + proxies_.push_back(new DescriptorReactionRuleProxy(this, rr)); + } + else if (rr.reactants().size() == 0) + { + proxies_.push_back(new ZerothOrderReactionRuleProxy(this, rr)); + } + else if (rr.reactants().size() == 1) + { + proxies_.push_back(new FirstOrderReactionRuleProxy(this, rr)); + } + else if (rr.reactants().size() == 2) + { + if (world_->has_structure(rr.reactants()[0])) + { + proxies_.push_back(new StructureSecondOrderReactionRuleProxy(this, rr, 0)); + } + else if (world_->has_structure(rr.reactants()[1])) + { + proxies_.push_back(new StructureSecondOrderReactionRuleProxy(this, rr, 1)); + } + else + { + proxies_.push_back(new SecondOrderReactionRuleProxy(this, rr)); + } + } + else + { + throw IllegalState(""Never get here""); + } + + proxies_.back().initialize(); + } + diffusion_proxy_offset_ = proxies_.size(); + + // const std::vector& species(model_->species_attributes()); + const std::vector& species(world_->species()); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + if (!world_->has_species(*i)) + { + world_->reserve_pool(*i); //XXX: This must be deprecated. + } + + proxies_.push_back(create_diffusion_proxy(*i)); + } + + scheduler_.clear(); + event_ids_.resize(world_->num_subvolumes()); + for (Integer i(0); i < world_->num_subvolumes(); ++i) + { + event_ids_[i] = + scheduler_.add(std::shared_ptr( + new SubvolumeEvent(this, i, t()))); + } +} + +Real MesoscopicSimulator::dt(void) const +{ + return next_time() - t(); +} + +Real MesoscopicSimulator::next_time(void) const +{ + return scheduler_.next_time(); +} + +} // meso + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/MesoscopicWorld.hpp",".hpp","12314","423","#ifndef ECELL4_MESO_MESOSCOPIC_WORLD_HPP +#define ECELL4_MESO_MESOSCOPIC_WORLD_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +namespace meso +{ + +struct MoleculeInfo +{ + const Real D; + const std::string loc; +}; + +class MesoscopicWorld + : public WorldInterface +{ +public: + + typedef SubvolumeSpace::coordinate_type coordinate_type; + typedef MoleculeInfo molecule_info_type; + + typedef SubvolumeSpace::PoolBase PoolBase; + +public: + + MesoscopicWorld(const std::string& filename) + : cs_(new SubvolumeSpaceVectorImpl(Real3(1, 1, 1), Integer3(1, 1, 1))) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + this->load(filename); + } + + MesoscopicWorld(const Real3& edge_lengths = Real3(1, 1, 1)) + : cs_(new SubvolumeSpaceVectorImpl(edge_lengths, Integer3(1, 1, 1))) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); + } + + MesoscopicWorld(const Real3& edge_lengths, const Integer3& matrix_sizes) + : cs_(new SubvolumeSpaceVectorImpl(edge_lengths, matrix_sizes)) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); + } + + MesoscopicWorld(const Real3& edge_lengths, + const Integer3& matrix_sizes, std::shared_ptr rng) + : cs_(new SubvolumeSpaceVectorImpl(edge_lengths, matrix_sizes)), rng_(rng) + { + ; + } + + MesoscopicWorld(const Real3& edge_lengths, const Real subvolume_length); + MesoscopicWorld( + const Real3& edge_lengths, const Real subvolume_length, + std::shared_ptr rng); + + virtual ~MesoscopicWorld() + { + ; + } + + void bind_to(std::shared_ptr model) + { + if (std::shared_ptr bound_model = lock_model()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to MesoscopicWorld."" + << std::endl; + } + } + + this->model_ = model; + } + + void save(const std::string& filename) const + { +#ifdef WITH_HDF5 + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + rng_->save(fout.get()); + std::unique_ptr + group(new H5::Group(fout->createGroup(""SubvolumeSpace""))); + cs_->save_hdf5(group.get()); + extras::save_version_information(fout.get(), std::string(""ecell4-meso-"") + std::string(VERSION_INFO)); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void load(const std::string& filename) + { +#ifdef WITH_HDF5 + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-meso-0.0""; + try + { + const std::string version = extras::load_version_information(*fin); + if (!extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required << ""] or later is required.""; + throw NotSupported(ss.str()); + } + } + catch(H5::GroupIException not_found_error) + { + throw NotFound(""No version information was found.""); + } + + rng_->load(*fin); + const H5::Group group(fin->openGroup(""SubvolumeSpace"")); + cs_->load_hdf5(group); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + std::shared_ptr lock_model() const + { + return model_.lock(); + } + + inline const std::shared_ptr& rng() + { + return rng_; + } + + MoleculeInfo get_molecule_info(const Species& sp) const; + + const Real t() const; + void set_t(const Real& t); + const Integer num_subvolumes() const; + const Real subvolume() const; + const Real volume() const; + const Real3 subvolume_edge_lengths() const; + const Real3& edge_lengths() const; + + const Integer num_subvolumes(const Species& sp) const + { + return cs_->num_subvolumes(sp); + } + + const Integer3 matrix_sizes() const + { + return cs_->matrix_sizes(); + } + + coordinate_type global2coord(const Integer3& g) const; + Integer3 coord2global(const coordinate_type& c) const; + Integer3 position2global(const Real3& pos) const; + Integer position2coordinate(const Real3& pos) const; + + coordinate_type get_neighbor(const coordinate_type& c, const Integer rnd) const + { + return cs_->get_neighbor(c, rnd); + } + + void set_value(const Species& sp, const Real value); + Real get_value(const Species& sp) const; + Real get_value_exact(const Species& sp) const; + Integer num_molecules(const Species& sp) const; + Integer num_molecules_exact(const Species& sp) const; + Integer num_molecules(const Species& sp, const coordinate_type& c) const; + Integer num_molecules_exact(const Species& sp, const coordinate_type& c) const; + void add_molecules(const Species& sp, const Integer& num, const coordinate_type& c); + void remove_molecules(const Species& sp, const Integer& num, const coordinate_type& c); + + Integer num_molecules(const Species& sp, const Integer3& g) const + { + return cs_->num_molecules(sp, g); + } + + Integer num_molecules_exact(const Species& sp, const Integer3& g) const + { + return cs_->num_molecules_exact(sp, g); + } + + void add_molecules(const Species& sp, const Integer& num, const Integer3& g) + { + add_molecules(sp, num, global2coord(g)); + } + + void remove_molecules(const Species& sp, const Integer& num, const Integer3& g) + { + remove_molecules(sp, num, global2coord(g)); + } + + std::vector list_coordinates(const Species& sp) const; + std::vector list_coordinates_exact(const Species& sp) const; + + void add_molecules(const Species& sp, const Integer& num) + { + if (!cs_->has_species(sp)) + { + reserve_pool(sp); + } + + const std::shared_ptr& pool = get_pool(sp); + if (pool->loc() == """") + { + for (Integer i(0); i < num; ++i) + { + pool->add_molecules(1, rng_->uniform_int(0, num_subvolumes() - 1)); + } + + return; + } + + const Species st(pool->loc()); + if (!cs_->has_structure(st)) + { + throw NotFound(""no space to throw-in.""); + } + + Integer i(0); + while (i < num) + { + const coordinate_type j(rng_->uniform_int(0, num_subvolumes() - 1)); + if (cs_->check_structure(pool->loc(), j)) + { + pool->add_molecules(1, j); + i++; + } + } + } + + void add_molecules(const Species& sp, const Integer& num, + const std::shared_ptr shape) + { + if (!cs_->has_species(sp)) + { + reserve_pool(sp); + } + + const std::shared_ptr& pool = get_pool(sp); + + if (pool->loc() == """") + { + for (Integer i(0); i < num; ++i) + { + const Real3 pos(shape->draw_position(rng_)); + const coordinate_type& coord( + cs_->global2coord(cs_->position2global(pos))); + pool->add_molecules(1, coord); + } + + return; + } + + const Species st(pool->loc()); + if (!cs_->has_structure(st)) + { + throw NotFound(""no space to throw-in.""); + } + + Integer i(0); + while (i < num) + { + const Real3 pos(shape->draw_position(rng_)); + const Integer3 g(cs_->position2global(pos)); + const coordinate_type j(cs_->global2coord(g)); + if (cs_->check_structure(pool->loc(), j)) + { + pool->add_molecules(1, j); + i++; + } + } + } + + void remove_molecules(const Species& sp, const Integer& num) + { + std::vector a(num_subvolumes()); + for (coordinate_type c(0); c < num_subvolumes(); ++c) + { + a[c] = num_molecules_exact(sp, c); + } + + Integer num_tot(std::accumulate(a.begin(), a.end(), 0)); + if (num_tot < num) + { + throw_exception( + ""The number of molecules cannot be negative. ["", sp.serial(), ""]""); + } + + for (Integer i(0); i < num; ++i) + { + const Integer rnd1(rng_->uniform_int(0, num_tot - 1)); + Integer acct(0); + for (coordinate_type c(0); c < num_subvolumes(); ++c) + { + acct += a[c]; + if (acct > rnd1) + { + remove_molecules(sp, 1, c); + a[c] -= 1; + --num_tot; + break; + } + } + } + } + + std::pair, bool> new_particle(const Particle& p) + { + add_molecules(p.species(), 1, position2coordinate(p.position())); + return std::make_pair(std::make_pair(ParticleID(), p), true); + } + + std::pair, bool> new_particle( + const Species& sp, const Real3& pos) + { + add_molecules(sp, 1, position2coordinate(pos)); + const std::shared_ptr& pool = get_pool(sp); + return std::make_pair( + std::make_pair(ParticleID(), Particle(sp, pos, 0.0, pool->D())), true); + } + + void add_structure(const Species& sp, const std::shared_ptr& shape); + bool on_structure(const Species& sp, const coordinate_type& coord) const; + + bool has_structure(const Species& sp) const + { + return cs_->has_structure(sp); + } + + Real get_occupancy(const Species& sp, const coordinate_type& coord) const + { + return cs_->get_occupancy(sp, coord); + } + + Real get_occupancy(const Species& sp, const Integer3& g) const + { + return cs_->get_occupancy(sp, g); + } + + // Shape::dimension_kind get_dimension(const Species& sp) const + // { + // return cs_->get_dimension(sp); + // } + + inline bool on_structure(const Species& sp, const Integer3& g) const + { + return on_structure(sp, global2coord(g)); + } + + bool check_structure(const Species& sp, const Integer3& g) const + { + return cs_->check_structure(sp, g); + } + + bool check_structure(const Species::serial_type& serial, const coordinate_type& coord) const + { + return cs_->check_structure(serial, coord); + } + + Real get_volume(const Species& sp) const; + + bool has_species(const Species& sp) const + { + return cs_->has_species(sp); + } + + const std::vector& species() const; + std::vector list_species() const; + + std::vector > list_particles() const; + std::vector > list_particles_exact(const Species& sp) const; + std::vector > list_particles(const Species& sp) const; + + const std::shared_ptr& get_pool(const Species& sp) const + { + return cs_->get_pool(sp); + } + + const std::shared_ptr reserve_pool(const Species& sp) + { + const molecule_info_type minfo(get_molecule_info(sp)); + return cs_->reserve_pool(sp, minfo.D, minfo.loc); + } + + std::vector get_data(const Species& sp) const + { + return cs_->get_data(sp); + } + +private: + + std::unique_ptr cs_; + std::shared_ptr rng_; + + std::weak_ptr model_; +}; + +} // meso + +} // ecell4 + +#endif /* ECELL4_MESO_MESOSCOPIC_WORLD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/MesoscopicFactory.hpp",".hpp","2627","107","#ifndef ECELL4_MESO_MESOSCOPIC_FACTORY_HPP +#define ECELL4_MESO_MESOSCOPIC_FACTORY_HPP + +#include +#include +#include + +#include ""MesoscopicWorld.hpp"" +#include ""MesoscopicSimulator.hpp"" + + +namespace ecell4 +{ + +namespace meso +{ + +class MesoscopicFactory: + public SimulatorFactory +{ +public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef MesoscopicFactory this_type; + +public: + + MesoscopicFactory( + const Integer3& matrix_sizes = default_matrix_sizes(), + const Real subvolume_length = default_subvolume_length()) + : base_type(), rng_(), matrix_sizes_(matrix_sizes), subvolume_length_(subvolume_length) + { + ; // do nothing + } + + virtual ~MesoscopicFactory() + { + ; // do nothing + } + + static inline const Integer3 default_matrix_sizes() + { + return Integer3(1, 1, 1); + } + + static inline const Real default_subvolume_length() + { + return 0.0; + } + + this_type& rng(const std::shared_ptr& rng) + { + rng_ = rng; + return (*this); + } + + inline this_type* rng_ptr(const std::shared_ptr& rng) + { + return &(this->rng(rng)); //XXX: == this + } + +protected: + + virtual world_type* create_world(const Real3& edge_lengths) const + { + if (rng_) + { + if (matrix_sizes_ != default_matrix_sizes()) + { + return new world_type(edge_lengths, matrix_sizes_, rng_); + } + else if (subvolume_length_ != default_subvolume_length()) + { + return new world_type(edge_lengths, subvolume_length_, rng_); + } + else + { + throw NotSupported( + ""Either matrix_sizes or subvolume_length must be given.""); + } + } + if (matrix_sizes_ != default_matrix_sizes()) + { + return new world_type(edge_lengths, matrix_sizes_); + } + else if (subvolume_length_ != default_subvolume_length()) + { + return new world_type(edge_lengths, subvolume_length_); + } + return new world_type(edge_lengths); + } + +protected: + + std::shared_ptr rng_; + Integer3 matrix_sizes_; + Real subvolume_length_; +}; + +} // meso + +} // ecell4 + +#endif /* ECELL4_MESO_MESOSCOPIC_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/MesoscopicSimulator.hpp",".hpp","36155","1154","#ifndef ECELL4_MESO_MESOSCOPIC_SIMULATOR_HPP +#define ECELL4_MESO_MESOSCOPIC_SIMULATOR_HPP + +#include +#include +#include +#include +#include +#include + +#include ""MesoscopicWorld.hpp"" + +namespace ecell4 +{ + +namespace meso +{ + +class ReactionInfo +{ +public: + + typedef SubvolumeSpace::coordinate_type coordinate_type; + typedef Species element_type; + typedef std::vector container_type; + +public: + + ReactionInfo( + const Real t, + const container_type& reactants, + const container_type& products, + const coordinate_type coord) + : t_(t), reactants_(reactants), products_(products), coord_(coord) + {} + + ReactionInfo( + const ReactionInfo& another) + : t_(another.t()), reactants_(another.reactants()), products_(another.products()), + coord_(another.coordinate()) + {} + + Real t() const + { + return t_; + } + + const container_type& reactants() const + { + return reactants_; + } + + void add_reactant(const element_type& elem) + { + reactants_.push_back(elem); + } + + const container_type& products() const + { + return products_; + } + + void add_product(const element_type& elem) + { + products_.push_back(elem); + } + + coordinate_type coordinate() const + { + return coord_; + } + +protected: + + Real t_; + container_type reactants_, products_; + coordinate_type coord_; +}; + +class MesoscopicSimulator + : public SimulatorBase +{ +public: + + typedef SimulatorBase base_type; + typedef SubvolumeSpace::coordinate_type coordinate_type; + typedef ReactionInfo reaction_info_type; + +protected: + + class ReactionRuleProxyBase + { + public: + + ReactionRuleProxyBase() + : sim_() + { + ; + } + + ReactionRuleProxyBase(MesoscopicSimulator* sim) + : sim_(sim) + { + ; + } + + virtual ~ReactionRuleProxyBase() + { + ; + } + + inline const Integer get_coef(const Species& pttrn, const Species& sp) const + { + return sim_->model()->apply(pttrn, sp); + } + + virtual void initialize() = 0; + virtual const Real propensity(const coordinate_type& c) const = 0; + virtual void fire(const Real t, const coordinate_type& src) = 0; + + virtual void inc( + const Species& sp, const coordinate_type& c, const Integer val = +1) = 0; + + inline void dec(const Species& sp, const coordinate_type& c) + { + inc(sp, c, -1); + } + + protected: + + inline const std::shared_ptr& rng() const + { + return sim_->world()->rng(); + } + + inline const MesoscopicWorld& world() const + { + return (*sim_->world()); + } + + protected: + + MesoscopicSimulator* sim_; + }; + + class ReactionRuleProxy + : public ReactionRuleProxyBase + { + public: + + typedef ReactionRuleProxyBase base_type; + + ReactionRuleProxy() + : base_type() + { + ; + } + + ReactionRuleProxy(MesoscopicSimulator* sim, const ReactionRule& rr) + : base_type(sim), rr_(rr) + { + ; + } + + virtual ~ReactionRuleProxy() + { + ; + } + + const ReactionRule& reaction_rule() const + { + return rr_; + } + + virtual std::vector check_dependency(const Species& sp) const + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + std::vector coefs(reactants.size(), 0); + for (std::vector::size_type i = 0; i < coefs.size(); ++i) + { + coefs[i] = get_coef(reactants[i], sp); + } + return coefs; + } + + virtual void inc_with_coefs(const std::vector& coefs, + const coordinate_type& c, const Integer val = +1) = 0; + + inline const std::vector generate( + const ReactionRule::reactant_container_type& reactants) const + { + return sim_->model()->apply(rr_, reactants); + } + + std::pair draw(const coordinate_type& c) + { + const std::pair + retval(__draw(c)); + const std::vector reactions(generate(retval.first)); + + assert(retval.second > 0); + assert(retval.second >= static_cast(reactions.size())); + + if (reactions.size() == 0) + { + return std::make_pair(ReactionRule(), c); + } + else if (retval.second == 1) + { + return std::make_pair(reactions[0], c); + } + else + { + const std::vector::size_type + rnd2(static_cast::size_type>( + rng()->uniform_int(0, retval.second - 1))); + if (rnd2 >= reactions.size()) + { + return std::make_pair(ReactionRule(), c); + } + return std::make_pair(reactions[rnd2], c); + } + } + + virtual void fire(const Real t, const coordinate_type& src) + { + const std::pair + retval = this->draw(src); + + const ReactionRule& nextr = retval.first; + // const coordinate_type& dst = retval.second; + const ReactionRule::reactant_container_type& reactants(nextr.reactants()); + const ReactionRule::product_container_type& products(nextr.products()); + + assert(retval.second == src); + + for (ReactionRule::product_container_type::const_iterator + it(products.begin()); it != products.end(); ++it) + { + const Species& sp(*it); + + if (!sim_->world()->on_structure(sp, src)) + { + ; // do nothing except for update() + return; + } + } + + for (ReactionRule::reactant_container_type::const_iterator + it(reactants.begin()); it != reactants.end(); ++it) + { + sim_->decrement_molecules(*it, src); + } + + for (ReactionRule::product_container_type::const_iterator + it(products.begin()); it != products.end(); ++it) + { + sim_->increment_molecules(*it, src); + } + + sim_->add_last_reaction( + nextr, reaction_info_type(t, reactants, products, src)); + } + + protected: + + virtual std::pair + __draw(const coordinate_type& c) = 0; + + protected: + + ReactionRule rr_; + }; + + class ZerothOrderReactionRuleProxy + : public ReactionRuleProxy + { + public: + + typedef ReactionRuleProxy base_type; + + ZerothOrderReactionRuleProxy() + : base_type() + { + ; + } + + ZerothOrderReactionRuleProxy(MesoscopicSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr) + { + ; + } + + void inc_with_coefs(const std::vector& coefs, + const coordinate_type& c, const Integer val = +1) + { + ; // do nothing + } + + void inc(const Species& sp, const coordinate_type& c, const Integer val = +1) + { + ; // do nothing + } + + void initialize() + { + ; // do nothing + } + + std::pair __draw(const coordinate_type& c) + { + return std::make_pair(ReactionRule::reactant_container_type(), 1); + } + + const Real propensity(const coordinate_type& c) const + { + return rr_.k() * world().subvolume(); + } + }; + + class FirstOrderReactionRuleProxy + : public ReactionRuleProxy + { + public: + + typedef ReactionRuleProxy base_type; + + FirstOrderReactionRuleProxy() + : base_type(), num_tot1_() + { + ; + } + + FirstOrderReactionRuleProxy(MesoscopicSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr), num_tot1_(sim->world()->num_subvolumes()) + { + ; + } + + void inc_with_coefs(const std::vector& coefs, + const coordinate_type& c, const Integer val = +1) + { + num_tot1_[c] += coefs[0] * val; + } + + void inc(const Species& sp, const coordinate_type& c, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + const Integer coef(get_coef(reactants[0], sp)); + if (coef > 0) + { + num_tot1_[c] += coef * val; + } + } + + void initialize() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + std::fill(num_tot1_.begin(), num_tot1_.end(), 0); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[0], *i)); + if (coef > 0) + { + for (Integer j(0); j < world().num_subvolumes(); ++j) + { + num_tot1_[j] += coef * world().num_molecules_exact(*i, j); + } + } + } + } + + std::pair __draw(const coordinate_type& c) + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + const Real rnd1(rng()->uniform(0.0, num_tot1_[c])); + + Integer num_tot(0); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[0], *i)); + if (coef > 0) + { + num_tot += coef * world().num_molecules_exact(*i, c); + if (num_tot >= rnd1) + { + return std::make_pair( + ReactionRule::reactant_container_type(1, *i), coef); + } + } + } + + throw IllegalState(""FirstOrderReactionRuleProxy: Never reach here.""); + } + + const Real propensity(const coordinate_type& c) const + { + return (num_tot1_[c] > 0 ? num_tot1_[c] * rr_.k() : 0.0); + } + + protected: + + std::vector num_tot1_; + }; + + class SecondOrderReactionRuleProxy: + public ReactionRuleProxy + { + public: + + typedef ReactionRuleProxy base_type; + + SecondOrderReactionRuleProxy() + : base_type(), num_tot1_(0), num_tot2_(0), num_tot12_(0) + { + ; + } + + SecondOrderReactionRuleProxy(MesoscopicSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr), + num_tot1_(sim->world()->num_subvolumes()), + num_tot2_(sim->world()->num_subvolumes()), + num_tot12_(sim->world()->num_subvolumes()) + { + ; + } + + void inc_with_coefs(const std::vector& coefs, + const coordinate_type& c, const Integer val = +1) + { + num_tot1_[c] += coefs[0] * val; + num_tot2_[c] += coefs[1] * val; + num_tot12_[c] += coefs[0] * coefs[1] * val; + } + + void inc(const Species& sp, const coordinate_type& c, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + const Integer coef1(get_coef(reactants[0], sp)); + const Integer coef2(get_coef(reactants[1], sp)); + if (coef1 > 0 || coef2 > 0) + { + const Integer tmp(coef1 * val); + num_tot1_[c] += tmp; + num_tot2_[c] += coef2 * val; + num_tot12_[c] += coef2 * tmp; + } + } + + void initialize() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + std::fill(num_tot1_.begin(), num_tot1_.end(), 0); + std::fill(num_tot2_.begin(), num_tot2_.end(), 0); + std::fill(num_tot12_.begin(), num_tot12_.end(), 0); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef1(get_coef(reactants[0], *i)); + const Integer coef2(get_coef(reactants[1], *i)); + if (coef1 > 0 || coef2 > 0) + { + for (Integer j(0); j < world().num_subvolumes(); ++j) + { + const Integer num(world().num_molecules_exact(*i, j)); + const Integer tmp(coef1 * num); + num_tot1_[j] += tmp; + num_tot2_[j] += coef2 * num; + num_tot12_[j] += coef2 * tmp; + } + } + } + } + + std::pair __draw(const coordinate_type& c) + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + const Real rnd1(rng()->uniform(0.0, num_tot1_[c])); + + Integer num_tot(0), coef1(0); + std::vector::const_iterator itr1(species.begin()); + for (; itr1 != species.end(); ++itr1) + { + const Integer coef(get_coef(reactants[0], *itr1)); + if (coef > 0) + { + num_tot += coef * world().num_molecules_exact(*itr1, c); + if (num_tot >= rnd1) + { + coef1 = coef; + break; + } + } + } + + const Real rnd2( + rng()->uniform(0.0, num_tot2_[c] - get_coef(reactants[0], *itr1))); + + num_tot = 0; + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[1], *i)); + if (coef > 0) + { + const Integer num(world().num_molecules_exact(*i, c)); + num_tot += coef * (i == itr1 ? num - 1 : num); + if (num_tot >= rnd2) + { + ReactionRule::reactant_container_type exact_reactants(2); + exact_reactants[0] = *itr1; + exact_reactants[1] = *i; + return std::make_pair(exact_reactants, coef1 * coef); + } + } + } + + throw IllegalState(""SecondOrderReactionRuleProxy: Never reach here.""); + } + + const Real propensity(const coordinate_type& c) const + { + const Integer num = num_tot1_[c] * num_tot2_[c] - num_tot12_[c]; + return (num > 0 ? num * rr_.k() / world().subvolume(): 0.0); + } + + protected: + + std::vector num_tot1_, num_tot2_, num_tot12_; + }; + + class StructureSecondOrderReactionRuleProxy: + public ReactionRuleProxy + { + public: + + typedef ReactionRuleProxy base_type; + + StructureSecondOrderReactionRuleProxy() + : base_type(), num_tot_(0), stidx_(0), spidx_(0) + { + ; + } + + StructureSecondOrderReactionRuleProxy( + MesoscopicSimulator* sim, const ReactionRule& rr, + const ReactionRule::reactant_container_type::size_type stidx) + : base_type(sim, rr), num_tot_(sim->world()->num_subvolumes()), + stidx_(stidx), spidx_(stidx == 0 ? 1 : 0) + { + ; + } + + void inc_with_coefs(const std::vector& coefs, + const coordinate_type& c, const Integer val = +1) + { + num_tot_[c] += coefs[spidx_] * val; + } + + void inc(const Species& sp, const coordinate_type& c, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + const Integer coef(get_coef(reactants[spidx_], sp)); + if (coef > 0) + { + num_tot_[c] += coef * val; + } + } + + void initialize() + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + // if (world().get_dimension(reactants[stidx_]) != Shape::TWO) + // { + // throw NotSupported( + // ""A second order reaction is only acceptable"" + // "" with a structure with dimension two.""); + // } else + if (world().has_structure(reactants[spidx_])) + { + throw NotSupported( + ""A second order reaction between structures has no mean.""); + } + + const std::vector& species(world().list_species()); + std::fill(num_tot_.begin(), num_tot_.end(), 0); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[spidx_], *i)); + if (coef > 0) + { + for (Integer j(0); j < world().num_subvolumes(); ++j) + { + num_tot_[j] += coef * world().num_molecules_exact(*i, j); + } + } + } + } + + std::pair __draw(const coordinate_type& c) + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + const Real rnd1(rng()->uniform(0.0, num_tot_[c])); + + Integer tot(0); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[spidx_], *i)); + if (coef > 0) + { + tot += coef * world().num_molecules_exact(*i, c); + if (tot >= rnd1) + { + ReactionRule::reactant_container_type retval(2); + retval[spidx_] = *i; + retval[stidx_] = reactants[stidx_]; + return std::make_pair(retval, coef); + } + } + } + throw IllegalState(""StructureSecondOrderReactionRuleProxy: Never reach here.""); + } + + const Real propensity(const coordinate_type& c) const + { + const Real occupancy = world().get_occupancy(rr_.reactants()[stidx_], c); + return (num_tot_[c] > 0 ? num_tot_[c] * rr_.k() * occupancy : 0.0); + } + + protected: + + std::vector num_tot_; + ReactionRule::reactant_container_type::size_type stidx_, spidx_; + }; + + class DescriptorReactionRuleProxy + : public ReactionRuleProxy + { + public: + + typedef ReactionRuleProxy base_type; + typedef ReactionRuleDescriptor::state_container_type state_container_type; + + DescriptorReactionRuleProxy() + : base_type(), num_reactants_(), num_products_() + { + ; + } + + DescriptorReactionRuleProxy(MesoscopicSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr), num_reactants_(sim->world()->num_subvolumes()), + num_products_(sim->world()->num_subvolumes()) + { + ; + } + + virtual std::vector check_dependency(const Species& sp) const + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + const ReactionRule::product_container_type& products(rr_.products()); + std::vector coefs(reactants.size() + products.size(), 0); + for (std::size_t i = 0; i < reactants.size(); ++i) + { + coefs[i] = get_coef(reactants[i], sp); + } + for (std::size_t i = 0; i < products.size(); ++i) + { + coefs[i + reactants.size()] = get_coef(products[i], sp); + } + return coefs; + } + + void inc_with_coefs(const std::vector& coefs, + const coordinate_type& c, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + for (std::size_t i = 0; i < reactants.size(); ++i) + { + num_reactants_[c][i] += coefs[i] * val; + } + + const ReactionRule::product_container_type& products(rr_.products()); + for (std::size_t i = 0; i < products.size(); ++i) + { + num_products_[c][i] += coefs[i + reactants.size()] * val; + } + } + + void inc(const Species& sp, const coordinate_type& c, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + for (std::size_t i = 0; i < reactants.size(); ++i) + { + const Integer coef(get_coef(reactants[i], sp)); + if (coef > 0) + { + num_reactants_[c][i] += coef * val; + } + } + + const ReactionRule::product_container_type& products(rr_.products()); + for (std::size_t i = 0; i < products.size(); ++i) + { + const Integer coef(get_coef(products[i], sp)); + if (coef > 0) + { + num_products_[c][i] += coef * val; + } + } + } + + void initialize() + { + const std::vector& species(world().list_species()); + const std::size_t n_subvolumes = static_cast(world().num_subvolumes()); + + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + num_reactants_.resize(n_subvolumes); + for (std::size_t i = 0; i < n_subvolumes; ++i) + { + std::fill(num_reactants_[i].begin(), num_reactants_[i].end(), 0); + num_reactants_[i].resize(reactants.size(), 0); + } + + const ReactionRule::product_container_type& products(rr_.products()); + num_products_.resize(n_subvolumes); + for (std::size_t i = 0; i < n_subvolumes; ++i) + { + std::fill(num_products_[i].begin(), num_products_[i].end(), 0); + num_products_[i].resize(products.size(), 0); + } + + for (std::vector::const_iterator it(species.begin()); + it != species.end(); ++it) + { + const Species& sp(*it); + + for (std::size_t i = 0; i < reactants.size(); ++i) + { + const Integer coef(get_coef(reactants[i], sp)); + if (coef > 0) + { + for (std::size_t j = 0; j < n_subvolumes; ++j) + { + num_reactants_[j][i] += coef * world().num_molecules_exact(sp, j); + } + } + } + + for (std::size_t i = 0; i < products.size(); ++i) + { + const Integer coef(get_coef(products[i], sp)); + if (coef > 0) + { + for (std::size_t j = 0; j < n_subvolumes; ++j) + { + num_products_[j][i] += coef * world().num_molecules_exact(sp, j); + } + } + } + } + } + + std::pair __draw(const coordinate_type& c) + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + std::pair ret; + ret.second = 1; + + for (std::size_t i = 0; i < reactants.size(); ++i) + { + assert(num_reactants_[c][i] > 0); + const Real rnd(rng()->uniform(0.0, num_reactants_[c][i])); + Integer num_tot(0); + for (std::vector::const_iterator it(species.begin()); + it != species.end(); ++it) + { + const Species& sp(*it); + const Integer coef(get_coef(reactants[i], sp)); + if (coef > 0) + { + num_tot += coef * world().num_molecules_exact(sp, c); + if (num_tot >= rnd) + { + ret.first.push_back(sp); + ret.second *= coef; + break; + } + } + } + } + + assert(ret.first.size() == reactants.size()); + return ret; + } + + const Real propensity(const coordinate_type& c) const + { + assert(rr_.has_descriptor()); + const std::shared_ptr& ratelaw = rr_.get_descriptor(); + assert(ratelaw->is_available()); + const Real ret = ratelaw->propensity(num_reactants_[c], num_products_[c], world().subvolume(), world().t()); + return ret; + } + + virtual void fire(const Real t, const coordinate_type& src) + { + const std::pair + retval = this->draw(src); + + const ReactionRule& nextr = retval.first; + // const coordinate_type& dst = retval.second; + const ReactionRule::reactant_container_type& reactants(nextr.reactants()); + const ReactionRule::product_container_type& products(nextr.products()); + + assert(retval.second == src); + + for (ReactionRule::product_container_type::const_iterator + it(products.begin()); it != products.end(); ++it) + { + const Species& sp(*it); + + if (!sim_->world()->on_structure(sp, src)) + { + ; // do nothing except for update() + return; + } + } + + const std::shared_ptr& desc = nextr.get_descriptor(); + assert(desc->is_available()); + + const ReactionRuleDescriptor::coefficient_container_type& + reactant_coefficients(desc->reactant_coefficients()); + assert(reactants.size() == reactant_coefficients.size()); + for (std::size_t i = 0; i < reactants.size(); ++i) + { + assert(reactant_coefficients[i] >= 0); + for (std::size_t j = 0; j < (std::size_t)round(reactant_coefficients[i]); ++j) + { + sim_->decrement_molecules(reactants[i], src); + } + } + + const ReactionRuleDescriptor::coefficient_container_type& + product_coefficients(desc->product_coefficients()); + assert(products.size() == product_coefficients.size()); + for (std::size_t i = 0; i < products.size(); ++i) + { + assert(product_coefficients[i] >= 0); + for (std::size_t j = 0; j < (std::size_t)round(product_coefficients[i]); ++j) + { + sim_->increment_molecules(products[i], src); + } + } + + sim_->add_last_reaction( + nextr, reaction_info_type(t, reactants, products, src)); + } + + protected: + + std::vector num_reactants_, num_products_; + }; + + class DiffusionProxy + : public ReactionRuleProxyBase + { + public: + + typedef ReactionRuleProxyBase base_type; + + protected: + + typedef std::pair > + dependency_type; + typedef std::vector dependency_container_type; + + public: + + DiffusionProxy() + : base_type(), pool_(), dependencies_() + { + ; + } + + DiffusionProxy(MesoscopicSimulator* sim, const Species& sp) + : base_type(sim), pool_(sim->world()->get_pool(sp)), dependencies_() + { + ; + } + + virtual ~DiffusionProxy() + { + ; + } + + coordinate_type draw(const coordinate_type& c) + { + const Real3 lengths(sim_->world()->subvolume_edge_lengths()); + const Real px(1.0 / (lengths[0] * lengths[0])), + py(1.0 / (lengths[1] * lengths[1])), + pz(1.0 / (lengths[2] * lengths[2])); + + const Real rnd1(sim_->world()->rng()->uniform(0.0, px + py + pz)); + + if (rnd1 < px * 0.5) + { + return sim_->world()->get_neighbor(c, 0); + } + else if (rnd1 < px) + { + return sim_->world()->get_neighbor(c, 1); + } + else if (rnd1 < px + py * 0.5) + { + return sim_->world()->get_neighbor(c, 2); + } + else if (rnd1 < px + py) + { + return sim_->world()->get_neighbor(c, 3); + } + else if (rnd1 < px + py + pz * 0.5) + { + return sim_->world()->get_neighbor(c, 4); + } + return sim_->world()->get_neighbor(c, 5); + } + + void initialize() + { + const Real D = pool_->D(); + const Real3 lengths(sim_->world()->subvolume_edge_lengths()); + const Real px(1.0 / (lengths[0] * lengths[0])), + py(1.0 / (lengths[1] * lengths[1])), + pz(1.0 / (lengths[2] * lengths[2])); + k_ = 2 * D * (px + py + pz); + } + + const Real propensity(const coordinate_type& c) const + { + return k_ * pool_->num_molecules(c); + } + + void inc(const Species& sp, const coordinate_type& c, const Integer val = +1) + { + ; // do nothing + } + + virtual void fire(const Real t, const coordinate_type& src) + { + const coordinate_type dst = this->draw(src); + + if (dst == src) + { + ; // do nothing except for update() + return; + } + + if (!sim_->world()->check_structure(pool_->loc(), dst)) + { + ; // do nothing except for update() + return; + } + + { + // sim_->decrement(pool_, src); + // sim_->increment(pool_, dst); + + pool_->remove_molecules(1, src); + pool_->add_molecules(1, dst); + + for (dependency_container_type::const_iterator i(dependencies_.begin()); + i != dependencies_.end(); ++i) + { + (*i).first->inc_with_coefs((*i).second, src, -1); + (*i).first->inc_with_coefs((*i).second, dst, +1); + } + } + + sim_->interrupt(dst); + } + + void set_dependency(ReactionRuleProxy* proxy) + { + const std::vector coefs = proxy->check_dependency(pool_->species()); + if (std::count(coefs.begin(), coefs.end(), 0) < std::distance(coefs.begin(), coefs.end())) + { + dependencies_.push_back(std::make_pair(proxy, coefs)); + } + } + + protected: + + const std::shared_ptr pool_; + Real k_; + + dependency_container_type dependencies_; + }; + + struct SubvolumeEvent + : public Event + { + public: + + SubvolumeEvent(MesoscopicSimulator* sim, const coordinate_type& c, const Real& t) + : Event(t), sim_(sim), coord_(c) + { + update(); + } + + virtual ~SubvolumeEvent() + { + ; + } + + virtual void fire() + { + assert(proxy_ != NULL); + sim_->reset_last_reactions(); + proxy_->fire(time_, coord_); + update(); + } + + virtual void interrupt(Real const& t) + { + time_ = t; + update(); + } + + void update() + { + const std::pair + retval = sim_->draw_next_reaction(coord_); + time_ += retval.first; + proxy_ = retval.second; + } + + protected: + + MesoscopicSimulator* sim_; + coordinate_type coord_; + + ReactionRuleProxyBase* proxy_; + }; + +public: + + MesoscopicSimulator( + std::shared_ptr world, + std::shared_ptr model) + : base_type(world, model) + { + initialize(); + } + + MesoscopicSimulator(std::shared_ptr world) + : base_type(world) + { + initialize(); + } + + // SimulatorTraits + Real dt(void) const; + Real next_time(void) const; + + void step(void); + bool step(const Real & upto); + + // Optional members + virtual bool check_reaction() const + { + return last_reactions_.size() > 0; + } + + std::vector > last_reactions() const + { + return last_reactions_; + } + + void add_last_reaction(const ReactionRule& rr, const reaction_info_type& ri) + { + last_reactions_.push_back(std::make_pair(rr, ri)); + } + + void reset_last_reactions() + { + last_reactions_.clear(); + } + + /** + * recalculate reaction propensities and draw the next time. + */ + void initialize(); + + inline std::shared_ptr rng() + { + return (*world_).rng(); + } + + void interrupt(const coordinate_type& coord) + { + interrupted_ = coord; + } + +protected: + + DiffusionProxy* create_diffusion_proxy(const Species& sp); + + void interrupt_all(const Real& t); + std::pair + draw_next_reaction(const coordinate_type& c); + + void increment_molecules(const Species& sp, const coordinate_type& c); + void decrement_molecules(const Species& sp, const coordinate_type& c); + void increment(const std::shared_ptr& pool, const coordinate_type& c); + void decrement(const std::shared_ptr& pool, const coordinate_type& c); + void check_model(void); + +protected: + + std::vector > last_reactions_; + + boost::ptr_vector proxies_; + boost::ptr_vector::size_type diffusion_proxy_offset_; + + EventScheduler scheduler_; + std::vector event_ids_; + coordinate_type interrupted_; +}; + +} // meso + +} // ecell4 + +#endif /* ECELL4_MESO_MESOSCOPIC_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/MesoscopicWorld.cpp",".cpp","9911","355","#include +#include +#include ""MesoscopicWorld.hpp"" + +#ifdef WIN32_MSC +#include +#endif + +namespace ecell4 +{ + +namespace meso +{ + +#ifdef WIN32_MSC +double round(const double x) +{ + return floor(x + 0.5); +} +#endif + +MesoscopicWorld::MesoscopicWorld(const Real3& edge_lengths, const Real subvolume_length) + : cs_(new SubvolumeSpaceVectorImpl(edge_lengths, Integer3(round(edge_lengths[0] / subvolume_length), round(edge_lengths[1] / subvolume_length), round(edge_lengths[2] / subvolume_length)))) +{ + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); +} + +MesoscopicWorld::MesoscopicWorld( + const Real3& edge_lengths, const Real subvolume_length, + std::shared_ptr rng) + : cs_(new SubvolumeSpaceVectorImpl(edge_lengths, Integer3(round(edge_lengths[0] / subvolume_length), round(edge_lengths[1] / subvolume_length), round(edge_lengths[2] / subvolume_length)))), rng_(rng) +{ + ; +} + +MoleculeInfo MesoscopicWorld::get_molecule_info(const Species& sp) const +{ + const bool with_D(sp.has_attribute(""D"")); + const bool with_loc(sp.has_attribute(""location"")); + + Real D(0.0); + std::string loc(""""); + + if (with_loc) + { + loc = sp.get_attribute_as(""location""); + } + + if (with_D) + { + D = sp.get_attribute_as(""D""); + } + else + { + if (std::shared_ptr bound_model = lock_model()) + { + Species newsp(bound_model->apply_species_attributes(sp)); + if (newsp.has_attribute(""D"")) + { + D = newsp.get_attribute_as(""D""); + } + + if (!with_loc && newsp.has_attribute(""location"")) + { + loc = newsp.get_attribute_as(""location""); + } + } + } + + MoleculeInfo info = {D, loc}; + return info; +} + +std::vector > + MesoscopicWorld::list_particles() const +{ + SerialIDGenerator pidgen; + const std::vector& species_list(species()); + const Real3 lengths(subvolume_edge_lengths()); + + std::vector > retval; + for (std::vector::const_iterator i(species_list.begin()); + i != species_list.end(); ++i) + { + const std::shared_ptr& pool = get_pool(*i); + for (coordinate_type j(0); j < num_subvolumes(); ++j) + { + const Integer num(pool->num_molecules(j)); + const Integer3 g(coord2global(j)); + + for (Integer k(0); k < num; ++k) + { + const Real3 pos( + rng_->uniform(g.col * lengths[0], (g.col + 1) * lengths[0]), + rng_->uniform(g.row * lengths[1], (g.row + 1) * lengths[1]), + rng_->uniform(g.layer * lengths[2], (g.layer + 1) * lengths[2])); + retval.push_back( + std::make_pair(pidgen(), Particle(*i, pos, 0.0, pool->D()))); + } + } + } + return retval; +} + +std::vector > + MesoscopicWorld::list_particles_exact(const Species& sp) const +{ + SerialIDGenerator pidgen; + const Real3 lengths(subvolume_edge_lengths()); + + std::vector > retval; + if (has_species(sp)) + { + const std::shared_ptr& pool = get_pool(sp); + for (coordinate_type j(0); j < num_subvolumes(); ++j) + { + const Integer num(pool->num_molecules(j)); + const Integer3 g(coord2global(j)); + + for (Integer k(0); k < num; ++k) + { + const Real3 pos( + rng_->uniform(g.col * lengths[0], (g.col + 1) * lengths[0]), + rng_->uniform(g.row * lengths[1], (g.row + 1) * lengths[1]), + rng_->uniform(g.layer * lengths[2], (g.layer + 1) * lengths[2])); + retval.push_back( + std::make_pair(pidgen(), Particle(sp, pos, 0.0, pool->D()))); + } + } + } + return retval; +} + +std::vector > + MesoscopicWorld::list_particles(const Species& sp) const +{ + SerialIDGenerator pidgen; + const std::vector& species_list(species()); + const Real3 lengths(subvolume_edge_lengths()); + + std::vector > retval; + // MoleculeInfo info(get_molecule_info(sp)); + // for (coordinate_type j(0); j < num_subvolumes(); ++j) + // { + // const Integer num(num_molecules(sp, j)); + // const Integer3 g(coord2global(j)); + + // for (Integer k(0); k < num; ++k) + // { + // const Real3 pos( + // rng_->uniform(g.col * lengths[0], (g.col + 1) * lengths[0]), + // rng_->uniform(g.row * lengths[1], (g.row + 1) * lengths[1]), + // rng_->uniform(g.layer * lengths[2], (g.layer + 1) * lengths[2])); + // retval.push_back( + // std::make_pair(pidgen(), Particle(sp, pos, 0.0, info.D))); + // } + // } + for (std::vector::const_iterator i(species_list.begin()); + i != species_list.end(); ++i) + { + const Integer coef(count_species_matches(sp, *i)); + if (coef == 0) + { + continue; + } + + const std::shared_ptr& pool = get_pool(*i); + for (coordinate_type j(0); j < num_subvolumes(); ++j) + { + const Integer num(coef * pool->num_molecules(j)); + const Integer3 g(coord2global(j)); + + for (Integer k(0); k < num; ++k) + { + const Real3 pos( + rng_->uniform(g.col * lengths[0], (g.col + 1) * lengths[0]), + rng_->uniform(g.row * lengths[1], (g.row + 1) * lengths[1]), + rng_->uniform(g.layer * lengths[2], (g.layer + 1) * lengths[2])); + retval.push_back( + std::make_pair(pidgen(), Particle(*i, pos, 0.0, pool->D()))); + } + } + } + return retval; +} + +const Real3& MesoscopicWorld::edge_lengths() const +{ + return cs_->edge_lengths(); +} + +const Real3 MesoscopicWorld::subvolume_edge_lengths() const +{ + return cs_->subvolume_edge_lengths(); +} + +const Real MesoscopicWorld::t() const +{ + return cs_->t(); +} + +void MesoscopicWorld::set_t(const Real& t) +{ + cs_->set_t(t); +} + +void MesoscopicWorld::set_value(const Species& sp, const Real value) +{ + const Integer num1 = static_cast(value); + const Integer num2 = num_molecules_exact(sp); + if (num1 > num2) + { + add_molecules(sp, num1 - num2); + } + else if (num1 < num2) + { + remove_molecules(sp, num2 - num1); + } +} + +Real MesoscopicWorld::get_value(const Species& sp) const +{ + return cs_->get_value(sp); +} + +Real MesoscopicWorld::get_value_exact(const Species& sp) const +{ + return cs_->get_value_exact(sp); +} + +const Integer MesoscopicWorld::num_subvolumes() const +{ + return cs_->num_subvolumes(); +} + +const Real MesoscopicWorld::subvolume() const +{ + return cs_->subvolume(); +} + +const Real MesoscopicWorld::volume() const +{ + return cs_->volume(); +} + +MesoscopicWorld::coordinate_type MesoscopicWorld::global2coord(const Integer3& g) const +{ + return cs_->global2coord(g); +} + +Integer3 MesoscopicWorld::coord2global(const MesoscopicWorld::coordinate_type& c) const +{ + return cs_->coord2global(c); +} + +Integer3 MesoscopicWorld::position2global(const Real3& pos) const +{ + return cs_->position2global(pos); +} + +Integer MesoscopicWorld::position2coordinate(const Real3& pos) const +{ + return cs_->position2coordinate(pos); +} + +Integer MesoscopicWorld::num_molecules(const Species& sp) const +{ + return cs_->num_molecules(sp); +} + +Integer MesoscopicWorld::num_molecules_exact(const Species& sp) const +{ + return cs_->num_molecules_exact(sp); +} + +Integer MesoscopicWorld::num_molecules( + const Species& sp, const MesoscopicWorld::coordinate_type& c) const +{ + return cs_->num_molecules(sp, c); +} + +Integer MesoscopicWorld::num_molecules_exact( + const Species& sp, const MesoscopicWorld::coordinate_type& c) const +{ + return cs_->num_molecules_exact(sp, c); +} + +void MesoscopicWorld::add_molecules( + const Species& sp, const Integer& num, const MesoscopicWorld::coordinate_type& c) +{ + if (!cs_->has_species(sp)) + { + this->reserve_pool(sp); + } + cs_->add_molecules(sp, num, c); +} + +void MesoscopicWorld::remove_molecules( + const Species& sp, const Integer& num, const MesoscopicWorld::coordinate_type& c) +{ + cs_->remove_molecules(sp, num, c); +} + +std::vector +MesoscopicWorld::list_coordinates(const Species& sp) const +{ + return cs_->list_coordinates(sp); // std::move? +} + +std::vector +MesoscopicWorld::list_coordinates_exact(const Species& sp) const +{ + return cs_->list_coordinates_exact(sp); // std::move? +} + +const std::vector& MesoscopicWorld::species() const +{ + return cs_->species(); +} + +std::vector MesoscopicWorld::list_species() const +{ + return cs_->list_species(); +} + +void MesoscopicWorld::add_structure( + const Species& sp, const std::shared_ptr& shape) +{ + cs_->add_structure(sp, shape); +} + +bool MesoscopicWorld::on_structure( + const Species& sp, const coordinate_type& coord) const +{ + if (has_species(sp)) + { + const std::shared_ptr& pool = get_pool(sp); + return (pool->loc() == """" || cs_->check_structure(pool->loc(), coord)); + } + + const molecule_info_type minfo(get_molecule_info(sp)); + return (minfo.loc == """" || cs_->check_structure(minfo.loc, coord)); +} + +Real MesoscopicWorld::get_volume(const Species& sp) const +{ + return cs_->get_volume(sp); +} + +} // meso + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/samples/simple-meso.cpp",".cpp","1281","57","#include + +#include +#include +#include + +#include + +#include +#include +typedef ecell4::meso::MesoscopicWorld world_type; +typedef ecell4::meso::MesoscopicSimulator simulator_type; + + +namespace ecell4 +{ + +void run() +{ + const Real L(10); + const Real L_2(L * 0.5); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(30, 30, 30); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(Species(""A"", 0.0025, 1, ""C"")); + + std::shared_ptr + rng(new GSLRandomNumberGenerator()); + rng->seed(0); + // rng->seed(time(NULL)); + + std::shared_ptr world( + new world_type(edge_lengths, matrix_sizes, rng)); + world->bind_to(model); + + world->add_structure( + Species(""C""), + std::shared_ptr( + new Sphere(Real3(L_2, L_2, L_2), L_2 * 0.8))); + + world->add_molecules(Species(""A""), 1800); + + simulator_type sim(world, model); + sim.run(1.0); +} + +} // ecell4 + +/** + * main function + */ +int main(int argc, char** argv) +{ + ecell4::run(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/meso/tests/MesoscopicSimulator_test.cpp",".cpp","1480","52","#define BOOST_TEST_MODULE ""MesoscopicSimulator_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include + +#include +#include + +using namespace ecell4; +using namespace ecell4::meso; + +BOOST_AUTO_TEST_CASE(MesoscopicSimulator_test_step) +{ + std::shared_ptr model(new NetworkModel()); + Species sp1(""A""); + Species sp2(""B""); + ReactionRule rr1; + rr1.set_k(5.0); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_reaction_rule(rr1); + + const Real L(1.0); + const Real3 edge_lengths(L, L, L); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + std::shared_ptr world( + new MesoscopicWorld(edge_lengths, Integer3(2, 3, 4), rng)); + + world->add_molecules(sp1, 10, 0); + world->add_molecules(sp2, 10, 23); + + MesoscopicSimulator sim(world, model); + + // sim.set_t(0.0); + sim.step(); + + BOOST_CHECK(0 < sim.t()); + BOOST_CHECK(sim.t() < std::numeric_limits::infinity()); + BOOST_CHECK(world->num_molecules(sp1, 0) == 9); + BOOST_CHECK(world->num_molecules(sp2, 0) == 1); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Domain.hpp",".hpp","2705","120","#ifndef ECELL4_EGFRD_DOMAIN_HPP +#define ECELL4_EGFRD_DOMAIN_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct ImmutativeDomainVisitor; + +template +struct MutativeDomainVisitor; + +template +class Domain +{ +public: + typedef Ttraits_ traits_type; + typedef std::size_t size_type; + typedef typename traits_type::world_type::length_type length_type; + typedef typename traits_type::world_type::position_type position_type; + typedef typename traits_type::world_type::particle_id_pair particle_id_pair; + typedef typename traits_type::domain_id_type identifier_type; + typedef typename traits_type::shell_id_type shell_id_type; + typedef typename traits_type::event_id_pair_type event_id_pair_type; + typedef typename traits_type::time_type time_type; + +public: + virtual ~Domain() {} + + Domain(identifier_type const& id) + : id_(id), last_time_(0.), dt_(0.) {} + + identifier_type const& id() const + { + return id_; + } + + event_id_pair_type const& event() const + { + return event_; + } + + event_id_pair_type& event() + { + return event_; + } + + time_type const& last_time() const + { + return last_time_; + } + + time_type& last_time() + { + return last_time_; + } + + time_type const& dt() const + { + return dt_; + } + + time_type& dt() + { + return dt_; + } + + virtual size_type num_shells() const = 0; + + virtual size_type multiplicity() const = 0; + + virtual char const* type_name() const = 0; + + virtual std::string as_string() const + { + return (boost::format( + ""%s(id=%s, event=%s, last_time=%.16g, dt=%.16g)"") % + type_name() % + boost::lexical_cast(id_).c_str() % + boost::lexical_cast(event_.first).c_str() % + last_time_ % dt_).str(); + } + + virtual void accept(ImmutativeDomainVisitor const&) const = 0; + + virtual void accept(MutativeDomainVisitor const&) = 0; + +protected: + identifier_type id_; + event_id_pair_type event_; + time_type last_time_; + time_type dt_; +}; + +template +inline std::basic_ostream& +operator<<(std::basic_ostream& lhs, + Domain const& rhs) +{ + lhs << rhs.as_string(); + return lhs; +} + +template +inline char const* retrieve_domain_type_name(Domain const&) +{ + return ""Domain""; +} + +} // egfrd +} // ecell4 +#endif /* DOMAIN_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/linear_algebra.hpp",".hpp","5077","194","#ifndef ECELL4_EGFRD_LINEAR_ALGEBRA_HPP +#define ECELL4_EGFRD_LINEAR_ALGEBRA_HPP + +#include +#include +#include +#include +#include +#include + +#include ""utils/array_traits.hpp"" + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +using ::ecell4::pow_2; + +// ---------------------------------------------------------------------------- +// is_vector + +template +struct is_vector: public std::false_type {}; + +template +struct is_vector, N_>: public std::true_type {}; + +// ---------------------------------------------------------------------------- +// is_matrix + +template +struct is_matrix: public std::false_type {}; + +template +struct is_matrix: public std::true_type {}; + +template +struct is_matrix, N2_>, 2>: public boost::mpl::true_ {}; + +// ---------------------------------------------------------------------------- +// is_scalar + +template +struct is_scalar: public std::is_arithmetic {}; + +// ---------------------------------------------------------------------------- +// is_vector3 + +template +struct is_vector3: public is_vector {}; + +// ---------------------------------------------------------------------------- +// matrix_adapter + +template +struct matrix_adapter{}; + +template +struct matrix_adapter +{ + typedef T_ matrix_type[N1_][N2_]; + typedef std::size_t matrix_size_type; + + static matrix_size_type get_extent(matrix_type const& first, + std::size_t idx) + { + switch (idx) + { + case 0: + return N1_; + case 1: + return N2_; + default: + throw std::out_of_range(""index out of range""); + } + } +}; + +template +inline std::size_t matrix_extent(Tmat const& mat, std::size_t dim) +{ + return matrix_adapter::get_extent(mat, dim); +} + +// ---------------------------------------------------------------------------- +// matrix_adapter + +template +inline T_ add( T_ const& p1, T_ const& p2, typename std::enable_if::value>::type* = 0) +{ + return p1 + p2; +} + +template +inline T_ subtract( T_ const& p1, T_ const& p2, typename std::enable_if::value>::type* = 0) +{ + return p1 - p2; +} + +template +inline T_ multiply( T_ const& p1, T_ const& p2, typename std::enable_if::value>::type* = 0) +{ + return p1 * p2; +} + +template +inline T_ divide( T_ const& p1, T_ const& p2, typename std::enable_if::value>::type* = 0) +{ + return p1 / p2; +} + +template +inline T_ modulo( T_ const& p1, T_ const& p2 ) +{ + T_ r = p1 % p2; + if (r != 0 && (r > 0) == (p2 < 0)) + { + r += p2; + } + return r; +} + +template<> +inline float modulo( float const& p1, float const& p2 ) +{ + float r = std::fmod(p1, p2); + if (r != 0 && (r > 0) == (p2 < 0)) + { + r += p2; + } + return r; +} + +template<> +inline double modulo( double const& p1, double const& p2 ) +{ + double r = std::fmod(p1, p2); + if (r != 0 && (r > 0) == (p2 < 0)) + { + r += p2; + } + return r; +} + +template +inline T_ multiply(T_ const& p1, M_ const& p2, typename std::enable_if< + boost::mpl::and_, is_matrix >::value>::type* = 0) +{ + BOOST_ASSERT(matrix_extent(p2, 0) == 3 && matrix_extent(p2, 1) == 3); + T_ retval; + retval[0] = multiply(p1[0], p2[0][0]) + + multiply(p1[1], p2[1][0]) + + multiply(p1[2], p2[2][0]); + retval[1] = multiply(p1[0], p2[0][1]) + + multiply(p1[1], p2[1][1]) + + multiply(p1[2], p2[2][1]); + retval[2] = multiply(p1[0], p2[0][2]) + + multiply(p1[1], p2[1][2]) + + multiply(p1[2], p2[2][2]); + return retval; +} + +template +inline T_ multiply(M_ const& p1, T_ const& p2, typename std::enable_if< + boost::mpl::and_, is_vector3 >::value>::type* = 0) +{ + BOOST_ASSERT(matrix_extent(p1, 0) == 3 && matrix_extent(p1, 1) == 3); + T_ retval; + retval[0] = multiply(p1[0][0], p2[0]) + + multiply(p1[0][1], p2[1]) + + multiply(p1[0][2], p2[2]); + retval[1] = multiply(p1[1][0], p2[0]) + + multiply(p1[1][1], p2[1]) + + multiply(p1[1][2], p2[2]); + retval[2] = multiply(p1[2][0], p2[0]) + + multiply(p1[2][1], p2[1]) + + multiply(p1[2][2], p2[2]); + return retval; +} + +template +typename std::enable_if::value, T>::type +create_vector(Args&& ... args) +{ + return T(std::forward(args)...); +} + +} // egfrd +} // ecell4 +#endif /* LINEAR_ALGEBRA_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/exceptions.hpp",".hpp","906","72","#ifndef ECELL4_EGFRD_EXCEPTIONS_HPP +#define ECELL4_EGFRD_EXCEPTIONS_HPP + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +class PropagationError + : public ecell4::Exception +{ +public: + + PropagationError(const std::string& str) + : str_(str) + { + ; + } + + virtual ~PropagationError() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +class NoSpace + : public ecell4::Exception +{ +public: + + NoSpace() + : str_() + { + ; + } + + NoSpace(const std::string& str) + : str_(str) + { + ; + } + + virtual ~NoSpace() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +} // egfrd +} // ecell4 +#endif /* EXCEPTIONS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/MatrixSpace.hpp",".hpp","19256","639","#ifndef ECELL4_EGFRD_MATRIX_SPACE_HPP +#define ECELL4_EGFRD_MATRIX_SPACE_HPP + +// #include +#include +#include +#include +#include +#include +#include +#include +// #include ""Vector3.hpp"" +#include ""Real3Type.hpp"" +#include ""sorted_list.hpp"" +#include ""utils/array_helper.hpp"" +#include ""utils/range.hpp"" + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +class MatrixSpace +{ +public: + typedef typename Tobj_::length_type length_type; + typedef Tkey_ key_type; + typedef Tobj_ mapped_type; + // typedef Vector3 position_type; + typedef Real3 position_type; + + // typedef std::pair value_type; + typedef std::pair value_type; + typedef std::vector all_values_type; + + typedef sorted_list > cell_type; + typedef boost::multi_array matrix_type; + typedef typename cell_type::size_type size_type; + typedef std::array + cell_index_type; + typedef std::array + cell_offset_type; + typedef std::unordered_map + key_to_value_mapper_type; + + typedef typename all_values_type::iterator iterator; + typedef typename all_values_type::const_iterator const_iterator; + typedef typename all_values_type::reference reference; + typedef typename all_values_type::const_reference const_reference; + + typedef Integer3 matrix_sizes_type; + +private: + typedef std::pair nonconst_value_type; + +public: + + MatrixSpace( + const position_type& edge_lengths, const matrix_sizes_type& matrix_sizes) + : edge_lengths_(edge_lengths), + cell_sizes_( + edge_lengths[0] / matrix_sizes[0], + edge_lengths[1] / matrix_sizes[1], + edge_lengths[2] / matrix_sizes[2]), + matrix_( + boost::extents[matrix_sizes[0]][matrix_sizes[1]][matrix_sizes[2]]) + { + ; + } + + // ~MatrixSpace() + // { + // std::cerr << ""MatrixSpace was released."" << std::endl; //XXX: DEBUG + // } + + inline cell_index_type index(const position_type& pos, + double t = 1e-10) const + { + return array_gen( + static_cast( + pos[0] / cell_sizes_[0]) % matrix_.shape()[0], + static_cast( + pos[1] / cell_sizes_[1]) % matrix_.shape()[1], + static_cast( + pos[2] / cell_sizes_[2]) % matrix_.shape()[2]); + } + + inline bool offset_index( + cell_index_type& i, + const cell_offset_type& o) const + { + if ((o[0] < 0 && static_cast(-o[0]) > i[0]) + || (matrix_.shape()[0] - o[0] <= i[0]) + || (o[1] < 0 && static_cast(-o[1]) > i[1]) + || (matrix_.shape()[1] - o[1] <= i[1]) + || (o[2] < 0 && static_cast(-o[2]) > i[2]) + || (matrix_.shape()[2] - o[2] <= i[2])) + { + return false; + } + i[0] += o[0]; + i[1] += o[1]; + i[2] += o[2]; + return true; + } + + inline position_type offset_index_cyclic(cell_index_type& i, + const cell_offset_type& o) const + { + position_type retval; + + if (o[0] < 0 && + static_cast(-o[0]) > i[0]) + { + typename matrix_type::size_type t( + (i[0] + matrix_.shape()[0] - (-o[0] % matrix_.shape()[0])) % + matrix_.shape()[0]); + retval[0] + = (o[0] - + static_cast + (t - i[0])) * cell_sizes_[0]; + i[0] = t; + } + else if (matrix_.shape()[0] - o[0] <= i[0]) + { + typename matrix_type::size_type t( + (i[0] + (o[0] % matrix_.shape()[0])) % matrix_.shape()[0]); + retval[0] + = (o[0] - + static_cast + (t - i[0])) * cell_sizes_[0]; + i[0] = t; + } + else + { + i[0] += o[0]; + } + + if (o[1] < 0 && + static_cast(-o[1]) > i[1]) + { + typename matrix_type::size_type t( + (i[1] + matrix_.shape()[1] - (-o[1] % matrix_.shape()[1])) % + matrix_.shape()[1]); + retval[1] = (o[1] - static_cast(t - i[1])) * cell_sizes_[1]; + i[1] = t; + } + else if (matrix_.shape()[1] - o[1] <= i[1]) + { + typename matrix_type::size_type t( + (i[1] + (o[1] % matrix_.shape()[1])) % matrix_.shape()[1]); + retval[1] = (o[1] - static_cast(t - i[1])) * cell_sizes_[1]; + i[1] = t; + } + else + { + i[1] += o[1]; + } + + if (o[2] < 0 && + static_cast(-o[2]) > i[2]) + { + typename matrix_type::size_type t( + (i[2] + matrix_.shape()[2] - (-o[2] % matrix_.shape()[2])) % + matrix_.shape()[2]); + retval[2] = (o[2] - static_cast(t - i[2])) * cell_sizes_[2]; + i[2] = t; + } + else if (matrix_.shape()[2] - o[2] <= i[2]) + { + typename matrix_type::size_type t( + (i[2] + (o[2] % matrix_.shape()[2])) % matrix_.shape()[2]); + retval[2] = (o[2] - static_cast(t - i[2])) * cell_sizes_[2]; + i[2] = t; + } + else + { + i[2] += o[2]; + } + + return retval; + } + + inline const cell_type& cell(const cell_index_type& i) const + { + return matrix_[i[0]][i[1]][i[2]]; + } + + inline cell_type& cell(const cell_index_type& i) + { + return matrix_[i[0]][i[1]][i[2]]; + } + + inline const position_type& edge_lengths() const + { + return edge_lengths_; + } + + inline const position_type& cell_sizes() const + { + return cell_sizes_; + } + + inline const matrix_sizes_type matrix_sizes() const + { + typedef typename matrix_type::size_type matrix_size_type; + const matrix_size_type* sizes(matrix_.shape()); + return matrix_sizes_type(sizes[0], sizes[1], sizes[2]); + } + + inline size_type size() const + { + return values_.size(); + } + + inline iterator update(iterator const& old_value, const value_type& v) + { + cell_type* new_cell(&cell(index(v.second.position()))); + cell_type* old_cell(0); + + if (old_value != values_.end()) + old_cell = &cell(index((*old_value).second.position())); + + if (new_cell == old_cell) + { + reinterpret_cast(*old_value) = v; + return old_value; + } + else + { + typename all_values_type::size_type index(0); + + if (old_cell) + { + reinterpret_cast(*old_value) = v; + + typename cell_type::iterator i( + old_cell->find(old_value - values_.begin())); + index = *i; + old_cell->erase(i); + new_cell->push(index); + } + else + { + index = values_.size(); + values_.push_back(v); + new_cell->push(index); + rmap_[v.first] = index; + } + return values_.begin() + index; + } + } + + inline std::pair update(const value_type& v) + { + cell_type* new_cell(&cell(index(v.second.position()))); + typename all_values_type::iterator old_value(values_.end()); + cell_type* old_cell(0); + + { + typename key_to_value_mapper_type::const_iterator i(rmap_.find(v.first)); + if (i != rmap_.end()) + { + old_value = values_.begin() + (*i).second; + old_cell = &cell(index(old_value->second.position())); + } + } + + if (new_cell == old_cell) + { + reinterpret_cast(*old_value) = v; + return std::pair(old_value, false); + } + else + { + typename all_values_type::size_type index(0); + + if (old_cell) + { + reinterpret_cast(*old_value) = v; + + typename cell_type::iterator i( + old_cell->find(old_value - values_.begin())); + index = *i; + old_cell->erase(i); + new_cell->push(index); + return std::pair(values_.begin() + index, false); + } + else + { + index = values_.size(); + values_.push_back(v); + new_cell->push(index); + rmap_[v.first] = index; + return std::pair(values_.begin() + index, true); + } + } + } + + inline bool erase(iterator const& i) + { + if (end() == i) + { + return false; + } + + typename all_values_type::size_type const old_index(i - values_.begin()); + + bool is_succeeded(cell(index((*i).second.position())).erase(old_index)); + BOOST_ASSERT(is_succeeded); + // BOOST_ASSERT(cell(index((*i).second.position())).erase(old_index)); + rmap_.erase((*i).first); + + typename all_values_type::size_type const last_index(values_.size() - 1); + + if (old_index < last_index) + { + value_type const& last(values_[last_index]); + cell_type& old_c(cell(index(last.second.position()))); + is_succeeded = old_c.erase(last_index); + BOOST_ASSERT(is_succeeded); + // BOOST_ASSERT(old_c.erase(last_index)); + old_c.push(old_index); + rmap_[last.first] = old_index; + reinterpret_cast(*i) = last; + } + values_.pop_back(); + return true; + } + + inline bool erase(const key_type& k) + { + typename key_to_value_mapper_type::const_iterator p(rmap_.find(k)); + if (rmap_.end() == p) + { + return false; + } + return erase(values_.begin() + (*p).second); + } + + inline void clear() + { + for (typename matrix_type::element *p(matrix_.data()), + *e(matrix_.data() + + matrix_.num_elements()); + p != e; ++p) + { + (*p).clear(); + } + rmap_.clear(); + } + + inline iterator begin() + { + return values_.begin(); + } + + inline const_iterator begin() const + { + return values_.begin(); + } + + inline iterator end() + { + return values_.end(); + } + + inline const_iterator end() const + { + return values_.end(); + } + + inline iterator find(const key_type& k) + { + typename key_to_value_mapper_type::const_iterator p(rmap_.find(k)); + if (rmap_.end() == p) + { + return values_.end(); + } + return values_.begin() + (*p).second; + } + + inline const_iterator find(const key_type& k) const + { + typename key_to_value_mapper_type::const_iterator p(rmap_.find(k)); + if (rmap_.end() == p) + { + return values_.end(); + } + return values_.begin() + (*p).second; + } + + template + inline void each_neighbor(const cell_index_type& idx, Tcollect_& collector) + { + if(size() == 0) + { + return; + } + each_neighbor_loops(idx, collector); + } + + template + inline void each_neighbor(const cell_index_type& idx, Tcollect_ const& collector) + { + if(size() == 0) + { + return; + } + each_neighbor_loops(idx, collector); + } + + template + inline void each_neighbor(const cell_index_type& idx, Tcollect_& collector) const + { + if(size() == 0) + { + return; + } + each_neighbor_loops(idx, collector); + } + + template + inline void each_neighbor(const cell_index_type& idx, Tcollect_ const& collector) const + { + if(size() == 0) + { + return; + } + each_neighbor_loops(idx, collector); + } + + template + inline void each_neighbor_cyclic(const cell_index_type& idx, + Tcollect_& collector) + { + if(size() == 0) + { + return; + } + each_neighbor_cyclic_loops(idx, collector); + } + + template + inline void each_neighbor_cyclic(const cell_index_type& idx, + Tcollect_ const& collector) + { + if(size() == 0) + { + return; + } + each_neighbor_cyclic_loops(idx, collector); + } + + template + inline void each_neighbor_cyclic(const cell_index_type& idx, + Tcollect_& collector) const + { + if(size() == 0) + { + return; + } + each_neighbor_cyclic_loops(idx, collector); + } + + template + inline void each_neighbor_cyclic(const cell_index_type& idx, + Tcollect_ const& collector) const + { + if(size() == 0) + { + return; + } + each_neighbor_cyclic_loops(idx, collector); + } + +private: + std::pair cell_range() + { + return std::make_pair( + matrix_.origin(), matrix_.origin() + matrix_.num_elements()); + } + + std::pair cell_range() const + { + return std::make_pair( + matrix_.origin(), matrix_.origin() + matrix_.num_elements()); + } + + template + inline void each_neighbor_loops(const cell_index_type& idx, + Tcollect_& collector) const + { + cell_offset_type off; + + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type _idx(idx); + if (!offset_index(_idx, off)) { + continue; + } + cell_type const& c(cell(_idx)); + for (typename cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + collector(values_.begin() + *i, position_type()); + } + } + } + } + } + + template + inline void each_neighbor_loops(const cell_index_type& idx, + Tcollect_& collector) + { + cell_offset_type off; + + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type _idx(idx); + if (!offset_index(_idx, off)) { + continue; + } + cell_type const& c(cell(_idx)); + for (typename cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + collector(values_.begin() + *i, position_type()); + } + } + } + } + } + + template + inline void each_neighbor_cyclic_loops(const cell_index_type& idx, + Tcollect_& collector) const + { + cell_offset_type off; + + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type _idx(idx); + const position_type pos_off(offset_index_cyclic(_idx, off)); + cell_type const& c(cell(_idx)); + for (typename cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + collector(values_.begin() + *i, pos_off); + } + } + } + } + } + + template + inline void each_neighbor_cyclic_loops(const cell_index_type& idx, + Tcollect_& collector) + { + cell_offset_type off; + + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type _idx(idx); + const position_type pos_off(offset_index_cyclic(_idx, off)); + cell_type const& c(cell(_idx)); + for (typename cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + collector(values_.begin() + *i, pos_off); + } + } + } + } + } + +private: + const position_type edge_lengths_; + const position_type cell_sizes_; + matrix_type matrix_; + key_to_value_mapper_type rmap_; + all_values_type values_; +}; + +template +static inline typename MatrixSpace::cell_index_type& +operator+=( + typename MatrixSpace::cell_index_type& lhs, + const typename MatrixSpace::cell_offset_type& rhs) +{ + rhs[0] += lhs[0]; + rhs[1] += lhs[1]; + rhs[2] += lhs[2]; + return rhs; +} + +template +struct is_sized >: std::true_type {}; + +template +struct range_size > +{ + typedef typename MatrixSpace::size_type type; +}; + +template +struct range_size_retriever > +{ + typedef MatrixSpace argument_type; + typedef typename range_size::type result_type; + + result_type operator()(argument_type const& range) const + { + return range.size(); + } +}; + +} // egfrd +} // ecell4 +#endif /* MATRIX_SPACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ShellID.hpp",".hpp","954","44","#ifndef ECELL4_EGFRD_SHELL_ID_HPP +#define ECELL4_EGFRD_SHELL_ID_HPP + +#include +#include +// #include ""Identifier.hpp"" +#include + +namespace ecell4 +{ +namespace egfrd +{ + +struct ShellID: public ecell4::Identifier +{ + typedef ecell4::Identifier base_type; + + ShellID(value_type const& value = value_type(0, 0)) + : base_type(value) {} +}; + +template +inline std::basic_ostream& operator<<(std::basic_ostream& strm, + const ShellID& v) +{ + strm << ""ShellID("" << v().first << "":"" << v().second << "")""; + return strm; +} + +} //egfrd +} //ecell4 + +namespace std { +template<> +struct hash +{ + std::size_t operator()(ecell4::egfrd::ShellID const& val) const + { + return static_cast(val().first ^ val().second); + } +}; +} // std +#endif /* SHELL_ID_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Logger.cpp",".cpp","5810","243","#include +#include +#include +#include +#include +#include +#include +#include +// #include //XXX: disabled pattern matching once +#include ""Logger.hpp"" +#include ""ConsoleAppender.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +class LoggerManagerRegistry +{ +private: + typedef std::pair > entry_type; + // typedef std::pair > entry_type; +public: + void register_logger_manager(char const* logger_name_pattern, + std::shared_ptr const& manager) + { + managers_.push_back(entry_type(entry_type::first_type(logger_name_pattern), manager)); + } + + std::shared_ptr + get_default_logger_manager() const + { + return default_manager_; + } + + std::shared_ptr + operator()(char const* logger_name) const + { + if (!logger_name) + { + return default_manager_; + } + + // char const* const logger_name_end(logger_name + std::strlen(logger_name)); + // for (entry_type const& i: managers_) + // { + // if (boost::regex_match(logger_name, logger_name_end, i.first)) + // return i.second; + // } + const std::string _logger_name(logger_name); + for(entry_type const& i: managers_) + { + if (_logger_name == i.first) + { + return i.second; + } + } + + BOOST_ASSERT(default_manager_.get()); + return default_manager_; + } + + LoggerManagerRegistry(): default_manager_(new LoggerManager(""default"")) + { + default_manager_->add_appender(std::shared_ptr(new ConsoleAppender())); + } + +private: + std::vector managers_; + std::shared_ptr default_manager_; +}; + +static LoggerManagerRegistry registry; + +void LoggerManager::register_logger_manager( + char const* logger_name_pattern, + std::shared_ptr const& manager) +{ + registry.register_logger_manager(logger_name_pattern, manager); +} + +std::shared_ptr LoggerManager::get_logger_manager(char const* logger_name_pattern) +{ + return registry(logger_name_pattern); +} + +std::shared_ptr Logger::manager() const +{ + const_cast(this)->ensure_initialized(); + return manager_; +} + +Logger& Logger::get_logger(char const* name) +{ + static std::map> loggers; + + auto inserted(loggers.emplace(std::string(name), nullptr)); + if (inserted.second) + { + std::unique_ptr log(new Logger(registry, name)); + inserted.first->second = std::move(log); + } + return *(inserted.first->second); +} + +char const* Logger::stringize_error_level(enum level lv) +{ + static char const* names[] = { + ""OFF"", + ""DEBUG"", + ""INFO"", + ""WARN"", + ""ERROR"", + ""FATAL"" + }; + return static_cast(lv) >= sizeof(names) / sizeof(*names) ? ""???"": names[lv]; +} + +Logger::~Logger() +{ +} + +struct invoke_appender +{ + void operator()(std::shared_ptr const& appender) const + { + const char* chunks[] = { formatted_msg, NULL }; + (*appender)(level, name, chunks); + } + + invoke_appender(enum Logger::level level, + const char* name, char const *formatted_msg) + : level(level), name(name), + formatted_msg(formatted_msg) {} + + enum Logger::level const level; + char const* const name; + char const* const formatted_msg; +}; + +void Logger::level(enum Logger::level level) +{ + ensure_initialized(); + level_ = level; +} + +enum Logger::level Logger::level() const +{ + const_cast(this)->ensure_initialized(); + return level_; +} + +void Logger::logv(enum level lv, char const* format, va_list ap) +{ + ensure_initialized(); + + if (lv < level_) + { + return; + } + + char buf[1024]; + vsnprintf(buf, sizeof(buf), format, ap); + + std::for_each(appenders_.begin(), appenders_.end(), + invoke_appender(lv, name_.c_str(), buf)); +} + +void Logger::flush() +{ + ensure_initialized(); + + for(const auto& appender : appenders_) + { + appender->flush(); + } + return; +} + +inline void Logger::ensure_initialized() +{ + if (!manager_) + { + std::shared_ptr manager(registry_(name_.c_str())); + std::vector > appenders(manager->appenders()); + level_ = manager->level(); + appenders_.swap(appenders); + manager->manage(this); + manager_ = manager; + } +} + +Logger::Logger(LoggerManagerRegistry const& registry, char const* name) + : registry_(registry), name_(name), manager_() {} + +void LoggerManager::level(enum Logger::level level) +{ + /* synchronized { */ + level_ = level; + for(const auto& managed_logger : managed_loggers_) + { + managed_logger->level(level); + } + /* } */ +} + +enum Logger::level LoggerManager::level() const +{ + return level_; +} + +char const* LoggerManager::name() const +{ + return name_.c_str(); +} + +std::vector > const& LoggerManager::appenders() const +{ + /* synchronized() { */ + return appenders_; + /* } */ +} + +void LoggerManager::add_appender(std::shared_ptr const& appender) +{ + /* synchronized() { */ + appenders_.push_back(appender); + /* } */ +} + +LoggerManager::LoggerManager(char const* name, enum Logger::level level) + : name_(name), level_(level) {} + +void LoggerManager::manage(Logger* logger) +{ + /* synchronized { */ + managed_loggers_.insert(logger); + /* }} */ +} +LogAppender::~LogAppender() {} +} // egfrd +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ReactionRecorderWrapper.hpp",".hpp","3208","141","#ifndef ECELL4_EGFRD_REACTION_RECORDER_WRAPPER_HPP +#define ECELL4_EGFRD_REACTION_RECORDER_WRAPPER_HPP + +#include +#include +#include +#include ""ReactionRecorder.hpp"" +#include ""ReactionRecord.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +template +class ReactionRecorderWrapper + : public ReactionRecorder +{ +public: + + typedef ReactionRecorder base_type; + + typedef typename base_type::reaction_record_type reaction_record_type; + typedef typename reaction_record_type::particle_id_pair particle_id_pair; + typedef typename reaction_record_type::reaction_rule_id_type reaction_rule_id_type; + typedef typename reaction_record_type::reactants_type reactants_type; + typedef typename reaction_record_type::products_type products_type; + +public: + + /** + * The following class is almost same with ReactionRecord now. + * This should be deprecated, or replaced with ReactionRecord. + */ + class ReactionInfo + { + public: + + typedef particle_id_pair element_type; + typedef std::vector container_type; + + public: + + ReactionInfo( + const Real t, const container_type& reactants, const container_type& products) + : t_(t), reactants_(reactants), products_(products) + {} + + ReactionInfo(const ReactionInfo& another) + : t_(another.t()), reactants_(another.reactants()), products_(another.products()) + {} + + Real t() const + { + return t_; + } + + const container_type& reactants() const + { + return reactants_; + } + + void add_reactant(const element_type& elem) + { + reactants_.push_back(elem); + } + + const container_type& products() const + { + return products_; + } + + void add_product(const element_type& elem) + { + products_.push_back(elem); + } + + protected: + + Real t_; + container_type reactants_, products_; + }; + + // typedef reaction_record_type reaction_info_type; + typedef ReactionInfo reaction_info_type; + +public: + + ReactionRecorderWrapper() + : backend_() + { + ; + } + + virtual ~ReactionRecorderWrapper() + { + ; + } + + virtual void operator()(reaction_record_type const& rec) + { + if (backend_) + { + (*backend_)(rec); + } + + last_reactions_.push_back(std::make_pair( + rec.reaction_rule_id(), reaction_info_type(0.0, rec.reactants(), rec.products()))); + } + + const std::vector >& last_reactions() const + { + return last_reactions_; + } + + void clear() + { + last_reactions_.clear(); + } + + std::shared_ptr const& backend() const + { + return backend_; + } + + std::shared_ptr& backend() + { + return backend_; + } + +protected: + + std::vector > last_reactions_; + std::shared_ptr backend_; +}; + + +} // egfrd +} // ecell4 +#endif /* REACTION_RECORDER_WRAPPER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/PotentialField.hpp",".hpp","3530","143","#ifndef ECELL4_EGFRD_POTENTIAL_FIELD_HPP +#define ECELL4_EGFRD_POTENTIAL_FIELD_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +class PotentialField +{ +public: + + typedef Tcontainer container_type; + typedef RandomNumberGenerator rng_type; + typedef std::pair pid_particle_pair; + +public: + + virtual ~PotentialField() + { + ; + } + + virtual bool try_move(rng_type& rng, const pid_particle_pair& p, const Real3& newpos, const container_type& space) + { + return true; + } +}; + +template +class ShapedHardbodyPotentialField + : public PotentialField +{ +public: + + typedef PotentialField base_type; + typedef typename base_type::container_type container_type; + typedef typename base_type::pid_particle_pair pid_particle_pair; + typedef typename base_type::rng_type rng_type; + +public: + + ShapedHardbodyPotentialField(const std::shared_ptr& shape) + : shape_(shape) + { + ; + } + + bool try_move(rng_type& rng, const pid_particle_pair& p, const Real3& newpos, const container_type& space) + { + return (shape_->is_inside(newpos) <= 0.0); + } + +protected: + + std::shared_ptr shape_; +}; + +template +class ShapedDiscretePotentialField + : public PotentialField +{ +public: + + typedef PotentialField base_type; + typedef typename base_type::container_type container_type; + typedef typename base_type::pid_particle_pair pid_particle_pair; + typedef typename base_type::rng_type rng_type; + +public: + + ShapedDiscretePotentialField(const std::shared_ptr& shape, const Real& threshold) + : shape_(shape), threshold_(threshold) + { + ; + } + + bool try_move(rng_type& rng, const pid_particle_pair& p, const Real3& newpos, const container_type& space) + { + const Real3& oldpos(p.second.position()); + if (shape_->is_inside(newpos) <= 0.0 || shape_->is_inside(oldpos) > 0.0) + { + return true; + } + + const Real rnd = rng.uniform(0.0, 1.0); + return (rnd < threshold_); + } + +protected: + + std::shared_ptr shape_; + Real threshold_; +}; + +template +class LeashPotentialField + : public PotentialField +{ +public: + + typedef PotentialField base_type; + typedef typename base_type::container_type container_type; + typedef typename base_type::pid_particle_pair pid_particle_pair; + typedef typename base_type::rng_type rng_type; + + typedef std::unordered_map particle_id_position_map_type; + +public: + + LeashPotentialField(const Real radius) + : radius_(radius) + { + ; + } + + bool try_move(rng_type& rng, const pid_particle_pair& p, const Real3& newpos, const container_type& space) + { + particle_id_position_map_type::const_iterator it = centers_.find(p.first); + if (it == centers_.end()) + { + centers_.insert(particle_id_position_map_type::value_type(p.first, p.second.position())); + return (space.distance(p.second.position(), newpos) <= radius_); + } + return (space.distance((*it).second, newpos) <= radius_); + } + +protected: + + Real radius_; + particle_id_position_map_type centers_; +}; + +} // egfrd +} // ecell4 +#endif /* POTENTIAL_FIELD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ShapedDomain.hpp",".hpp","878","38","#ifndef ECELL4_EGFRD_SHAPED_DOMAIN_HPP +#define ECELL4_EGFRD_SHAPED_DOMAIN_HPP + +#include ""Domain.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ +template +class ShapedDomain: public Domain +{ +public: + typedef Ttraits_ traits_type; + typedef typename traits_type::domain_id_type identifier_type; + typedef typename traits_type::world_type::length_type length_type; + typedef typename traits_type::world_type::traits_type::position_type position_type; + typedef Domain base_type; + +public: + virtual ~ShapedDomain() {} + + virtual position_type const& position() const = 0; + + virtual position_type& position() = 0; + + virtual length_type const& size() const = 0; + + virtual length_type& size() = 0; + + ShapedDomain(identifier_type const& id) + : base_type(id) {} +}; + +} // egfrd +} // ecell4 +#endif /* SHAPED_DOMAIN_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Logger.hpp",".hpp","4049","180","#ifndef ECELL4_EGFRD_LOGGER_HPP +#define ECELL4_EGFRD_LOGGER_HPP + +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +class LogAppender; +class LoggerManager; +class LoggerManagerRegistry; + +class Logger +{ +public: + enum level + { + L_OFF = 0, + L_DEBUG = 1, + L_INFO = 2, + L_WARNING = 3, + L_ERROR = 4, + L_FATAL = 5 + }; + +public: + ~Logger(); + + Logger(const Logger&) = delete; + Logger& operator=(const Logger&) = delete; + + + LoggerManager const& logging_manager() const; + + void level(enum level level); + + enum level level() const; + + char const* name() const + { + return name_.c_str(); + } + + std::shared_ptr manager() const; + + void debug(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_DEBUG, format, ap); + va_end(ap); + } + + void info(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_INFO, format, ap); + va_end(ap); + } + + void warn(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_WARNING, format, ap); + va_end(ap); + } + + void error(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_ERROR, format, ap); + va_end(ap); + } + + void fatal(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_FATAL, format, ap); + va_end(ap); + } + + void log(enum level lv, char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(lv, format, ap); + va_end(ap); + } + + void logv(enum level lv, char const* format, va_list ap); + + void flush(); + + Logger(LoggerManagerRegistry const& registry, char const* name); + + static Logger& get_logger(char const* name); + + static char const* stringize_error_level(enum level lv); + +private: + void ensure_initialized(); + +protected: + LoggerManagerRegistry const& registry_; + std::string const name_; + std::shared_ptr manager_; + enum level level_; + std::vector > appenders_; +}; + +class LoggerManager +{ + friend class Logger; + +public: + + LoggerManager(const LoggerManager&) = delete; + LoggerManager& operator=(const LoggerManager&) = delete; + + void level(enum Logger::level level); + + enum Logger::level level() const; + + char const* name() const; + + std::vector > const& appenders() const; + + void add_appender(std::shared_ptr const& appender); + + LoggerManager(char const* name, enum Logger::level level = Logger::L_WARNING); + // LoggerManager(char const* name, enum Logger::level level = Logger::L_INFO); + + static void register_logger_manager(char const* logger_name_pattern, + std::shared_ptr const& manager); + + static std::shared_ptr get_logger_manager(char const* logger_name_patern); + +protected: + void manage(Logger* logger); + +protected: + std::string const name_; + enum Logger::level level_; + std::set managed_loggers_; + std::vector > appenders_; +}; + +class LogAppender +{ +public: + virtual ~LogAppender(); + + virtual void flush() = 0; + + virtual void operator()(enum Logger::level lv, + char const* name, char const** chunks) = 0; +}; + +#define LOG_DEBUG(args) if (log_.level() == Logger::L_DEBUG) log_.debug args + +#define LOG_INFO(args) if (enum Logger::level const level = log_.level()) if (level <= Logger::L_INFO) log_.info args + +#define LOG_WARNING(args) if (enum Logger::level const level = log_.level()) if (level <= Logger::L_WARNING) log_.warn args + +#define LOG_ERROR(args) if (enum Logger::level const level = log_.level()) if (level <= Logger::L_ERROR) log_.error args + +} //egfrd +} //ecell4 +#endif /* LOGGER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ReactionRuleInfo.hpp",".hpp","3127","121","#ifndef ECELL4_EGFRD_REACTION_RULE_INFO_HPP +#define ECELL4_EGFRD_REACTION_RULE_INFO_HPP + +#include +#include +#include +#include +#include ""twofold_container.hpp"" + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +class ReactionRuleInfo +{ +public: + typedef Tsid_ species_id_type; + +private: + typedef std::vector species_id_vector; + +public: + typedef species_id_vector species_id_range; + typedef Tid_ identifier_type; + typedef Trate_ rate_type; + + identifier_type const& id() const + { + return id_; + } + + species_id_range const& get_products() const + { + return products_; + } + + twofold_container const& get_reactants() const + { + return reactants_; + } + + rate_type k() const + { + return k_; + } + + template + ReactionRuleInfo(identifier_type const& id, rate_type const& k, + Tr1_ const& reactants, Tr2_ const& products) + : id_(id), k_(k) + { + std::copy(boost::begin(reactants), + boost::end(reactants), + std::back_inserter(reactants_)); + std::copy(boost::begin(products), + boost::end(products), + std::back_inserter(products_)); + } + + ReactionRuleInfo(): id_(), k_(), reactants_(), products_() {} + + bool operator==(ReactionRuleInfo const& rhs) const + { + return id_ == rhs.id(); + } + + std::string c_str() const + { + std::ostringstream os; + if (this->reactants_.size() == 2) { + os << this->reactants_[0] << "" + "" << this->reactants_[1] << "" ""; + } else if (this->reactants_.size() == 1) { + os << this->reactants_[0] << "" ""; + } else { + os << ""Invalid reactants size "" << this->reactants_.size() << "" ""; + } + os << "" ==> ""; + if (this->products_.size() == 2) { + os << this->products_[0] << "" + "" << this->products_[1] << "" ""; + } else if (this->products_.size() == 1) { + os << this->products_[0] << "" ""; + } else { + os << ""Invalid reactants size "" << this->products_.size() << "" ""; + } + os << "" K: "" << this->k_; + return std::string( os.str() ); + } + +private: + identifier_type id_; + rate_type k_; + twofold_container reactants_; + species_id_vector products_; +}; + +template +bool print_reaction_rule_vector( + std::vector> const &rrv) +{ + for(ReactionRuleInfo const& rr : rrv) + { + std::cout << rr.c_str() << std::endl; + } + std::cout << ""============================================================="" << std::endl; + return true; +} + +template +inline bool valid(ReactionRuleInfo const& r) +{ + return r.get_reactants().size() != 0; +} + +} // egfrd +} // ecell4 +#endif /* REACTION_RULE_INFO_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/egfrd.hpp",".hpp","6887","263","#ifndef ECELL4_EGFRD_EGFRD_HPP +#define ECELL4_EGFRD_EGFRD_HPP + +#include +#include +#include ""World.hpp"" +#include ""EGFRDSimulator.hpp"" +#include ""BDSimulator.hpp"" + +namespace ecell4 +{ + +namespace egfrd +{ + +typedef World > EGFRDWorld; +typedef EGFRDWorld::molecule_info_type MoleculeInfo; +typedef EGFRDSimulator> DefaultEGFRDSimulator; +typedef BDSimulator> DefaultBDSimulator; + +typedef DefaultEGFRDSimulator::reaction_info_type ReactionInfo; +// typedef BDSimulator::reaction_info_type ReactionInfo; + +class EGFRDFactory + : public SimulatorFactory +{ +public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef EGFRDFactory this_type; + +protected: + + typedef world_type::matrix_sizes_type matrix_sizes_type; + +public: + + EGFRDFactory( + const matrix_sizes_type& matrix_sizes = default_matrix_sizes(), + Real bd_dt_factor = default_bd_dt_factor(), + Integer dissociation_retry_moves = default_dissociation_retry_moves(), + Real user_max_shell_size = default_user_max_shell_size()) + : base_type(), rng_(), + matrix_sizes_(matrix_sizes), bd_dt_factor_(bd_dt_factor), + dissociation_retry_moves_(dissociation_retry_moves), + user_max_shell_size_(user_max_shell_size) + { + ; // do nothing + } + + virtual ~EGFRDFactory() + { + ; // do nothing + } + + static inline const matrix_sizes_type default_matrix_sizes() + { + return Integer3(0, 0, 0); + } + + static inline const Real default_bd_dt_factor() + { + return 0.0; + } + + static inline const Integer default_dissociation_retry_moves() + { + return -1; + } + + static inline const Real default_user_max_shell_size() + { + return 0.0; + } + + this_type& rng(const std::shared_ptr& rng) + { + rng_ = rng; + return (*this); + } + + inline this_type* rng_ptr(const std::shared_ptr& rng) + { + return &(this->rng(rng)); //XXX: == this + } + +protected: + + virtual world_type* create_world(const Real3& edge_lengths) const override + { + if (rng_) + { + if (matrix_sizes_ != default_matrix_sizes()) + { + return new world_type(edge_lengths, matrix_sizes_, rng_); + } + else + { + world_type* ret = new world_type(edge_lengths); + (*ret).set_rng(rng_); + return ret; + } + } + else if (matrix_sizes_ != default_matrix_sizes()) + { + return new world_type(edge_lengths, matrix_sizes_); + } + else + { + return new world_type(edge_lengths); + } + } + + virtual simulator_type* create_simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const override + { + if (user_max_shell_size_ != default_user_max_shell_size()) + { + return new simulator_type( + w, m, bd_dt_factor_, dissociation_retry_moves_, user_max_shell_size_); + } + else if (dissociation_retry_moves_ != default_dissociation_retry_moves()) + { + return new simulator_type( + w, m, bd_dt_factor_, dissociation_retry_moves_); + } + else if (bd_dt_factor_ != default_bd_dt_factor()) + { + return new simulator_type(w, m, bd_dt_factor_); + } + else + { + return new simulator_type(w, m); + } + } + +protected: + + std::shared_ptr rng_; + matrix_sizes_type matrix_sizes_; + Real bd_dt_factor_; + Integer dissociation_retry_moves_; + Real user_max_shell_size_; +}; + +class BDFactory + : public SimulatorFactory +{ +public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef BDFactory this_type; + +protected: + + typedef world_type::matrix_sizes_type matrix_sizes_type; + +public: + + BDFactory( + const matrix_sizes_type& matrix_sizes = default_matrix_sizes(), + Real bd_dt_factor = default_bd_dt_factor(), + Integer dissociation_retry_moves = default_dissociation_retry_moves()) + : base_type(), rng_(), + matrix_sizes_(matrix_sizes), bd_dt_factor_(bd_dt_factor), + dissociation_retry_moves_(dissociation_retry_moves) + { + ; // do nothing + } + + virtual ~BDFactory() + { + ; // do nothing + } + + static inline const matrix_sizes_type default_matrix_sizes() + { + return Integer3(0, 0, 0); + } + + static inline const Real default_bd_dt_factor() + { + return 0.0; + } + + static inline const Integer default_dissociation_retry_moves() + { + return -1; + } + + this_type& rng(const std::shared_ptr& rng) + { + rng_ = rng; + return (*this); + } + + inline this_type* rng_ptr(const std::shared_ptr& rng) + { + return &(this->rng(rng)); //XXX: == this + } + +protected: + + virtual world_type* create_world(const Real3& edge_lengths) const + { + if (rng_) + { + if (matrix_sizes_ != default_matrix_sizes()) + { + return new world_type(edge_lengths, matrix_sizes_, rng_); + } + else + { + world_type* ret = new world_type(edge_lengths); + (*ret).set_rng(rng_); + return ret; + } + } + else if (matrix_sizes_ != default_matrix_sizes()) + { + return new world_type(edge_lengths, matrix_sizes_); + } + else + { + return new world_type(edge_lengths); + } + } + + virtual simulator_type* create_simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const + { + if (dissociation_retry_moves_ != default_dissociation_retry_moves()) + { + return new simulator_type( + w, m, bd_dt_factor_, dissociation_retry_moves_); + } + else if (bd_dt_factor_ != default_bd_dt_factor()) + { + return new simulator_type(w, m, bd_dt_factor_); + } + else + { + return new simulator_type(w, m); + } + } + +protected: + + std::shared_ptr rng_; + matrix_sizes_type matrix_sizes_; + Real bd_dt_factor_; + Integer dissociation_retry_moves_; +}; + +} // egfrd +} // ecell4 + +#endif /* ECELL4_EGFRD_EGFRD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Real3Type.hpp",".hpp","1221","65","#ifndef ECELL4_EGFRD_REAL3_TRAITS_HPP +#define ECELL4_EGFRD_REAL3_TRAITS_HPP + +// This file containing the reference to the ecell4::Real3 and +// some template traits of ecell4::Real3. +// + +#include +#include +#include +#include +#include + +#include + +#include ""utils/array_traits.hpp"" +#include ""linear_algebra.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ +template +struct shape_position_type +{ + struct argument_is_not_a_shape; + static const std::size_t x = sizeof(argument_is_not_a_shape); +}; + +template +struct shape_length_type +{ + typedef typename element_type_of::type >::type>::type type; +}; + +template +struct is_vector: public std::true_type {}; + +template <> +struct element_type_of +{ + typedef Real3::value_type type; +}; + +template<> +struct shape_position_type +{ + typedef Real3 type; +}; + +template<> +struct shape_length_type +{ + typedef Real3::value_type type; +}; + +inline ::ecell4::Real3 shape_position(::ecell4::Real3 const &v) +{ + return v; +} + +} // egfrd +} // ecell4 +#endif /* POSITION3_TRAITS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/NetworkRulesAdapter.hpp",".hpp","6824","211","#ifndef ECELL4_EGFRD_NETWORK_RULES_ADAPTER +#define ECELL4_EGFRD_NETWORK_RULES_ADAPTER + +#include +#include +#include +#include ""ReactionRuleInfo.hpp"" +#include ""exceptions.hpp"" + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +// cf. epdp/NetworkRulesWrapper.hpp +// NetworkRulesAdapter will substitute for NetworkRulesWrapper +// which is instanciated in ParticleSimulatorTraitsBase. +// +// This class is called via query_reaction_rule function by EGFRDSimulator implemented in epdp, +// then, this class translates the query into ecell4::Species or ReactionRule object and +// consult ecell4::Model class. +//template + +ecell4::ReactionRule create_repulsive_reaction_rule( + const ecell4::Species& reactant1, const ecell4::Species& reactant2) +{ + ecell4::ReactionRule rr; + rr.set_k(0.0); + rr.add_reactant(reactant1); + rr.add_reactant(reactant2); + return rr; +} + +template +class NetworkRulesAdapter +{ +public: + + typedef ecell4::Model backend_type; // will not be used. + + typedef Trri_ reaction_rule_type; + typedef typename reaction_rule_type::species_id_type species_id_type; + typedef std::vector reaction_rule_vector; + typedef reaction_rule_vector reaction_rules; + typedef std::map + first_order_reaction_rule_vector_map; + typedef std::map, reaction_rule_vector> + second_order_reaction_rule_vector_map; + +public: + + reaction_rule_vector const& query_reaction_rule(species_id_type const& r1) const + { + typename first_order_reaction_rule_vector_map::const_iterator + i(first_order_cache_.find(r1)); + if (i == this->first_order_cache_.end()) + { + ecell4::Model::reaction_rule_container_type + reaction_rules_at_ecell4( + model_->query_reaction_rules(ecell4::Species(r1))); + + std::pair + x(first_order_cache_.insert(std::make_pair(r1, reaction_rule_vector()))); + for (std::vector::const_iterator + it(reaction_rules_at_ecell4.begin()); + it != reaction_rules_at_ecell4.end(); it++) + { + x.first->second.push_back(convert_reaction_rule_type(*it)); + } + return x.first->second; + } + return i->second; + } + + reaction_rule_vector const& query_reaction_rule( + species_id_type const& r1, species_id_type const& r2) const + { + typename second_order_reaction_rule_vector_map::const_iterator + i(second_order_cache_.find(std::make_pair(r1, r2))); + if (i == second_order_cache_.end()) + { + const ecell4::Species sp1(r1), sp2(r2); + + ecell4::Model::reaction_rule_container_type + reaction_rules_at_ecell4( + model_->query_reaction_rules(sp1, sp2)); + if (reaction_rules_at_ecell4.size() == 0) + { + reaction_rules_at_ecell4.push_back( + create_repulsive_reaction_rule(sp1, sp2)); + } + + std::pair + x(second_order_cache_.insert( + std::make_pair(std::make_pair(r1, r2), reaction_rule_vector()))); + for (std::vector::const_iterator + it(reaction_rules_at_ecell4.begin()); + it != reaction_rules_at_ecell4.end(); it++) + { + x.first->second.push_back(convert_reaction_rule_type(*it)); + } + return x.first->second; + } + return i->second; + } + + reaction_rule_vector const zeroth_order_reaction_rules() const + { + const ecell4::Model::reaction_rule_container_type& + rrs((*model_).reaction_rules()); + reaction_rule_vector retval; + for (ecell4::Model::reaction_rule_container_type::const_iterator + i(rrs.begin()); i != rrs.end(); ++i) + { + if ((*i).reactants().size() > 0) + { + continue; + } + + BOOST_ASSERT((*i).products().size() == 1); + retval.push_back(convert_reaction_rule_type(*i)); + } + return retval; + } + + NetworkRulesAdapter(std::shared_ptr model) + : model_(model) + { + ; + } + +protected: + + inline reaction_rule_type convert_reaction_rule_type(const ecell4::ReactionRule& rr) const + { + typedef typename reaction_rule_type::rate_type rate_type; + + reaction_rule_type retval; + std::vector products; + std::vector reactants; + rate_type rate; + + try + { + rate = boost::lexical_cast(rr.k()); + } + catch (boost::bad_lexical_cast&) + { + if (rr.k() == double(HUGE_VAL)) + { + rate = std::numeric_limits::infinity(); + } + else + { + throw; + } + } + + for (ecell4::ReactionRule::product_container_type::const_iterator + j(rr.products().begin()); j != rr.products().end(); ++j) + { + products.push_back(*j); + } + + ecell4::ReactionRule::reactant_container_type::const_iterator + r(rr.reactants().begin()); + switch (rr.reactants().size()) + { + case 0: + { + ; // with no cache + return reaction_rule_type(rr, rate, reactants, products); + } + case 1: + { + const species_id_type sid1(*r); + reactants.push_back(sid1); + return reaction_rule_type(rr, rate, reactants, products); + } + break; + case 2: + { + const species_id_type sid1(*r); + reactants.push_back(sid1); + ++r; + const species_id_type sid2(*r); + reactants.push_back(sid2); + return reaction_rule_type(rr, rate, reactants, products); + } + break; + default: + throw ::ecell4::IllegalState(""the number of reactants must be 1 or 2.""); + break; + } + return reaction_rule_type(); // never get here + } + +private: + + mutable first_order_reaction_rule_vector_map first_order_cache_; + mutable second_order_reaction_rule_vector_map second_order_cache_; + std::shared_ptr model_; +}; + +} // egfrd +} // ecell4 +#endif // ECELL4_EGFRD_NETWORK_RULES_ADAPTER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/World.hpp",".hpp","35674","1062","#ifndef ECELL4_EGFRD_WORLD_HPP +#define ECELL4_EGFRD_WORLD_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WITH_HDF5 +#include +#endif + +#include +#include ""./ParticleTraits.hpp"" // This refers ecell4::Particle +#include ""structures.hpp"" + +#include +#include ""ParticleContainer.hpp"" + +#include +#include +#include +#include ""generator.hpp"" +//#include ""ParticleID.hpp"" +//#include ""SpeciesTypeID.hpp"" +//#include ""SpeciesInfo.hpp"" +//#include ""SerialIDGenerator.hpp"" +// #include ""Structure.hpp"" +// #include ""Surface.hpp"" +// #include ""Region.hpp"" +#include ""geometry.hpp"" +//#include ""GSLRandomNumberGenerator.hpp"" +//#include ""Point.hpp"" // XXX: workaround. should be removed later. +#include ""Real3Type.hpp"" +#include ""utils/pair.hpp"" + +// #include ""ParticleSimulationStructure.hpp"" +// #include ""CuboidalRegion.hpp"" +// #include ""PlanarSurface.hpp"" +// #include ""CylindricalSurface.hpp"" +// #include ""SphericalSurface.hpp"" + +/* + * ParticleContainerBase + */ +#include ""utils/range.hpp"" +#include ""utils/collection_contains.hpp"" +#include ""generator.hpp"" +#include ""exceptions.hpp"" +#include ""MatrixSpace.hpp"" +#include ""ParticleContainer.hpp"" + +#include +#include ""Polygon.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct WorldTraitsBase +{ + typedef std::size_t size_type; + typedef ecell4::Real length_type; + typedef ecell4::Real D_type; + typedef ecell4::Real time_type; + typedef ecell4::ParticleID particle_id_type; + typedef ecell4::SerialIDGenerator particle_id_generator; + typedef ecell4::Species species_id_type; // std::string + // typedef ecell4::Species::serial_type species_id_type; // std::string + typedef ecell4::Particle particle_type; + typedef ecell4::Real3 position_type; + // typedef ecell4::GSLRandomNumberGenerator rng_type; + typedef ecell4::RandomNumberGenerator rng_type; + typedef ecell4::Model model_type; + + struct MoleculeInfo + { + const ecell4::Real radius; + const ecell4::Real D; + const std::string structure_id; + }; + + typedef MoleculeInfo molecule_info_type; + // typedef MoleculeInfo species_info_type; + // typedef SpeciesInfo + // species_info_type; + + // typedef Sphere particle_shape_type; + typedef ecell4::Sphere particle_shape_type; + typedef std::string structure_id_type; + + typedef std::pair particle_id_pair; + // typedef std::pair particle_id_pair; + typedef std::pair particle_id_pair_and_distance; + typedef std::vector particle_id_pair_and_distance_list; + typedef abstract_limited_generator particle_id_pair_generator; + + typedef ecell4::egfrd::Structure structure_type; + typedef ecell4::egfrd::Structure particle_simulation_structure_type; + typedef ecell4::egfrd::AABBRegion cuboidal_region_type; + + // typedef Structure structure_type; + // typedef ParticleSimulationStructure + // particle_simulation_structure_type; + // // typedef Surface surface_type; + // // typedef Region region_type; + // // typedef SphericalSurface spherical_surface_type; + // // typedef CylindricalSurface cylindrical_surface_type; + // // typedef PlanarSurface planar_surface_type; + // typedef CuboidalRegion cuboidal_region_type; + + static const Real tolerance(); + static const Real TOLERANCE; +}; + +template +const Real WorldTraitsBase::tolerance() +{ + return 1e-7; +} + +template +const Real WorldTraitsBase::TOLERANCE = WorldTraitsBase::tolerance(); + +template +struct WorldTraits: public WorldTraitsBase, TD_> +{ +public: + typedef WorldTraitsBase, TD_> base_type; + typedef typename base_type::length_type length_type; + typedef typename base_type::position_type position_type; + + template + static Tval_ apply_boundary(Tval_ const& v, position_type const& edge_lengths) + { + return v; + } + + template + static Tval_ periodic_transpose(Tval_ const& p0, Tval_ const& p1, Tval_ const& world_size) + { + return p0; + } + + template + static length_type distance(T1_ const& p0, T2_ const& p1, position_type const& edge_lengths) + { + return ecell4::egfrd::distance(p0, p1); + } + + template + static void each_neighbor(Toc_& oc, Tfun_& fun, Tsphere_ const& pos) + { + oc.each_neighbor(oc.index(pos), fun); + } + + template + static void each_neighbor(Toc_ const& oc, Tfun_& fun, Tsphere_ const& pos) + { + oc.each_neighbor(oc.index(pos), fun); + } +}; + +template +struct CyclicWorldTraits: public WorldTraitsBase, TD_> +{ +public: + typedef WorldTraitsBase, TD_> base_type; + typedef typename base_type::length_type length_type; + typedef typename base_type::position_type position_type; + + template + static Tval_ apply_boundary(Tval_ const& v, position_type const& edge_lengths) + { + return ecell4::egfrd::apply_boundary(v, edge_lengths); + } + + static length_type periodic_transpose(length_type const& p0, length_type const& p1, length_type const& world_size) + { + return ecell4::egfrd::periodic_transpose(p0, p1, world_size); + } + + static position_type periodic_transpose(position_type const& p0, position_type const& p1, position_type const& edge_lengths) + { + return ecell4::egfrd::periodic_transpose(p0, p1, edge_lengths); + } + + template + static length_type distance(T1_ const& p0, T2_ const& p1, T3_ const& edge_lengths) + { + return distance_cyclic(p0, p1, edge_lengths); + } + + template + static void each_neighbor(Toc_& oc, Tfun_& fun, Tsphere_ const& pos) + { + oc.each_neighbor_cyclic(oc.index(pos), fun); + } + + template + static void each_neighbor(Toc_ const& oc, Tfun_& fun, Tsphere_ const& pos) + { + oc.each_neighbor_cyclic(oc.index(pos), fun); + } +}; + +template +class World + : public ParticleContainer +{ +public: + + typedef Ttraits_ traits_type; + typedef ParticleContainer base_type; + + typedef ParticleContainer particle_container_type; + typedef typename traits_type::length_type length_type; + typedef typename traits_type::molecule_info_type molecule_info_type; + typedef typename traits_type::position_type position_type; + typedef typename traits_type::particle_type particle_type; + typedef typename traits_type::particle_id_type particle_id_type; + typedef typename traits_type::particle_id_generator particle_id_generator; + typedef typename traits_type::species_id_type species_id_type; + typedef typename traits_type::particle_shape_type particle_shape_type; + typedef typename traits_type::size_type size_type; + typedef typename traits_type::structure_id_type structure_id_type; + typedef typename traits_type::structure_type structure_type; + typedef typename traits_type::rng_type rng_type; + typedef typename traits_type::particle_id_pair particle_id_pair; + typedef typename traits_type::particle_id_pair_and_distance_list + particle_id_pair_and_distance_list; + typedef typename traits_type::model_type model_type; + + /** + * ParticleContainerBase + */ + typedef MatrixSpace particle_matrix_type; + typedef sized_iterator_range particle_id_pair_range; + typedef typename particle_matrix_type::matrix_sizes_type matrix_sizes_type; + typedef ecell4::ParticleSpaceCellListImpl particle_space_type; + typedef typename base_type::time_type time_type; + +protected: + + typedef std::map molecule_info_map; + typedef std::map > structure_map; + typedef std::set particle_id_set; + typedef std::map per_species_particle_id_set; + typedef select_second species_second_selector_type; + typedef select_second surface_second_selector_type; + +public: + + typedef boost::transform_iterator molecule_info_iterator; + typedef boost::transform_iterator surface_iterator; + typedef sized_iterator_range molecule_info_range; + typedef sized_iterator_range structures_range; + +public: + + World( + const position_type& edge_lengths = position_type(1, 1, 1), + const matrix_sizes_type& matrix_sizes = matrix_sizes_type(3, 3, 3)) + : ps_(new particle_space_type(edge_lengths, matrix_sizes)) + { + // rng_ = std::shared_ptr(new rng_type()); + rng_ = std::shared_ptr(new ecell4::GSLRandomNumberGenerator()); + (*rng_).seed(); + + add_world_structure(); + } + + World( + const position_type& edge_lengths, const matrix_sizes_type& matrix_sizes, + const std::shared_ptr& rng) + :ps_(new particle_space_type(edge_lengths, matrix_sizes)), rng_(rng) + { + add_world_structure(); + } + + World( + const position_type& edge_lengths, const matrix_sizes_type& matrix_sizes, + const std::shared_ptr& rng, const Polygon& poly) + :ps_(new particle_space_type(edge_lengths, matrix_sizes)), rng_(rng), + polygon_(poly) + { + add_world_structure(); + } + + World(const std::string filename) + : ps_(new particle_space_type(position_type(1, 1, 1), matrix_sizes_type(3, 3, 3))), rng_() + { + rng_ = std::shared_ptr(new ecell4::GSLRandomNumberGenerator()); + this->load(filename); + } + + virtual bool update_particle(const particle_id_type& pid, const particle_type& p) + { + if (molecule_info_map_.find(p.species()) == molecule_info_map_.end()) + { + register_species(p); + } + return (*ps_).update_particle(pid, p); + } + + molecule_info_range get_molecule_info_range() const + { + return molecule_info_range( + molecule_info_iterator( + molecule_info_map_.begin(), species_second_selector_type()), + molecule_info_iterator( + molecule_info_map_.end(), species_second_selector_type()), + molecule_info_map_.size()); + } + + bool add_structure(std::shared_ptr surface) + { + return structure_map_.insert(std::make_pair(surface->id(), surface)).second; + } + + virtual std::shared_ptr get_structure( + structure_id_type const& id) const + { + typename structure_map::const_iterator i(structure_map_.find(id)); + if (structure_map_.end() == i) + { + throw ::ecell4::NotFound(std::string(""Unknown surface (id="") + + boost::lexical_cast(id) + "")""); + } + return (*i).second; + } + + structures_range get_structures() const + { + return structures_range( + surface_iterator(structure_map_.begin(), surface_second_selector_type()), + surface_iterator(structure_map_.end(), surface_second_selector_type()), + structure_map_.size()); + } + + // particle_id_set get_particle_ids(species_id_type const& sid) const + // { + // typename per_species_particle_id_set::const_iterator i( + // particle_pool_.find(sid)); + // if (i == particle_pool_.end()) + // { + // throw ::ecell4::NotFound(std::string(""Unknown species (id="") + // + boost::lexical_cast(sid) + "")""); + // } + // return (*i).second; + // } + + /** ecell4::Space + */ + + inline std::shared_ptr& rng() + { + return rng_; + } + + void set_rng(const std::shared_ptr& rng) + { + rng_ = rng; + } + + virtual void save(const std::string& filename) const + { +#ifdef WITH_HDF5 + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + rng_->save(fout.get()); + pidgen_.save(fout.get()); + std::unique_ptr + group(new H5::Group(fout->createGroup(""ParticleSpace""))); + // ps_->save(group.get()); + ecell4::save_particle_space(*this, group.get()); + + /** matrix_sizes + */ + const matrix_sizes_type sizes = matrix_sizes(); + const hsize_t dims[] = {3}; + const H5::ArrayType sizes_type(H5::PredType::NATIVE_INT, 1, dims); + H5::Attribute attr_sizes( + group->createAttribute( + ""matrix_sizes"", sizes_type, H5::DataSpace(H5S_SCALAR))); + int data[] = { + static_cast(sizes[0]), + static_cast(sizes[1]), + static_cast(sizes[2]) + }; + attr_sizes.write(sizes_type, data); + + ecell4::extras::save_version_information(fout.get(), std::string(""ecell4-egfrd-"") + std::string(VERSION_INFO)); +#else + throw ecell4::NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + virtual void load(const std::string& filename) + { +#ifdef WITH_HDF5 + //XXX: structures will be lost. + //XXX: the order of particles in MatrixSpace will be lost. + //XXX: initialize Simulator + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-egfrd-0.0""; + try + { + const std::string version = ecell4::extras::load_version_information(*fin); + if (!ecell4::extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required << ""] or later is required.""; + throw ecell4::NotSupported(ss.str()); + } + } + catch(H5::GroupIException not_found_error) + { + throw ecell4::NotFound(""No version information was found.""); + } + + const H5::Group group(fin->openGroup(""ParticleSpace"")); + + /** matrix_sizes + */ + int data[3]; + const hsize_t dims[] = {3}; + const H5::ArrayType sizes_type(H5::PredType::NATIVE_INT, 1, dims); + group.openAttribute(""matrix_sizes"").read(sizes_type, data); + matrix_sizes_type sizes(data[0], data[1], data[2]); + //XXX: reset is called twice. see ecell4::load_particle_space + this->reset(edge_lengths(), sizes); + + // ps_->load(group); + ecell4::load_particle_space(group, this); + pidgen_.load(*fin); + rng_->load(*fin); +#else + throw ecell4::NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + virtual const length_type volume() const + { + const position_type& L(edge_lengths()); + return L[0] * L[1] * L[2]; + } + + virtual void reset(const position_type& lengths, const matrix_sizes_type& sizes) + { + std::unique_ptr + newps(new particle_space_type(lengths, sizes)); + ps_.swap(newps); + + ; // newps will be released here + } + + void set_value(const ecell4::Species& sp, const ecell4::Real value) + { + const ecell4::Integer num1 = static_cast(value); + const ecell4::Integer num2 = num_molecules_exact(sp); + if (num1 > num2) + { + add_molecules(sp, num1 - num2); + } + else if (num1 < num2) + { + remove_molecules(sp, num2 - num1); + } + } + + virtual ecell4::Real get_value(const ecell4::Species& sp) const + { + return static_cast(num_molecules(sp)); + } + + virtual ecell4::Real get_value_exact(const ecell4::Species& sp) const + { + return static_cast(num_molecules_exact(sp)); + } + + void bind_to(std::shared_ptr model) + { + if (std::shared_ptr bound_model = lock_model()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to BDWorld"" + << std::endl; + } + } + + model_ = model; + } + + std::shared_ptr lock_model() const + { + return model_.lock(); + } + + /** + * This is a function in the traits of ecell4::ParticleSpace. + * Be carefull about the difference from + * ""particle_id_pair new_particle(species_id_type const&, position_type const&)"". + */ + std::pair, bool> + new_particle(const ecell4::Species& sp, const position_type& pos) + { + const species_id_type sid(sp.serial()); + typename molecule_info_map::const_iterator i(molecule_info_map_.find(sid)); + molecule_info_type const minfo( + i != molecule_info_map_.end() ? (*i).second : get_molecule_info(sp)); + return new_particle(particle_type(sid, pos, minfo.radius, minfo.D)); + } + + std::pair, bool> + new_particle(const particle_type& p) + { + const particle_id_pair_and_distance_list overlapped( + check_overlap( + particle_shape_type(p.position(), p.radius()))); + if (overlapped.size() > 0) + { + return std::make_pair(std::make_pair(pidgen_(), p), false); + // return std::make_pair(std::make_pair(particle_id_type(), p), false); + } + else + { + const particle_id_type pid = pidgen_(); + return std::make_pair(std::make_pair(pid, p), update_particle(pid, p)); + } + } + + void add_molecules(const ecell4::Species& sp, const ecell4::Integer& num) + { + ecell4::extras::throw_in_particles(*this, sp, num, rng()); + } + + void add_molecules( + const ecell4::Species& sp, const ecell4::Integer& num, + const std::shared_ptr shape) + { + ecell4::extras::throw_in_particles(*this, sp, num, shape, rng()); + } + + void remove_molecules(const ecell4::Species& sp, const ecell4::Integer& num) + { + if (num < 0) + { + throw std::invalid_argument( + ""The number of molecules must be positive.""); + } + + std::vector > + particles(list_particles(sp)); + const Integer num_particles(particles.size()); + if (num_particles < num) + { + throw std::invalid_argument( + ""The number of molecules cannot be negative.""); + } + + shuffle((*rng_), particles); + for (std::vector >::const_iterator + i(particles.begin()); i != particles.begin() + num; ++i) + { + remove_particle((*i).first); + } + } + + /** + * draw attributes of species and return it as a molecule info. + * @param sp a species + * @return info a molecule info + */ + molecule_info_type get_molecule_info(ecell4::Species const& sp) const + { + ecell4::Real radius(0.0), D(0.0); + std::string structure_id(""world""); + + if (sp.has_attribute(""radius"") && sp.has_attribute(""D"")) + { + radius = sp.get_attribute_as(""radius""); + D = sp.get_attribute_as(""D""); + if (sp.has_attribute(""structure_id"")) + { + structure_id = sp.get_attribute_as(""structure_id""); + } + } + else if (std::shared_ptr bound_model = lock_model()) + { + ecell4::Species newsp(bound_model->apply_species_attributes(sp)); + + if (newsp.has_attribute(""radius"") + && newsp.has_attribute(""D"")) + { + radius = newsp.get_attribute_as(""radius""); + D = newsp.get_attribute_as(""D""); + } + + if (newsp.has_attribute(""structure_id"")) + { + structure_id = newsp.get_attribute_as(""structure_id""); + } + } + + if (radius <= 0.0) + { + std::stringstream msg; + msg << ""A particle with invalid size ["" << radius << ""] was given.""; + throw ecell4::IllegalArgument(msg.str()); + } + + molecule_info_type info = {radius, D, structure_id}; + return info; + } + +protected: + + const molecule_info_type& register_species(const particle_type& p) + { + const molecule_info_type defaults = {p.radius(), p.D(), ""world""}; + const species_id_type sp(p.species()); + molecule_info_type info = defaults; + // molecule_info_type info(get_molecule_info(sp, defaults)); + molecule_info_map_.insert(std::make_pair(sp, info)); + return (*molecule_info_map_.find(sp)).second; + } + + void add_world_structure() + { + typedef typename traits_type::cuboidal_region_type cuboidal_region_type; + typedef typename cuboidal_region_type::shape_type + cuboidal_region_shape_type; + + this->add_structure( + std::shared_ptr( + new cuboidal_region_type( + ""world"", cuboidal_region_shape_type( + position_type(0, 0, 0), edge_lengths())))); + // const position_type& center(edge_lengths() * 0.5); + // this->add_structure( + // std::shared_ptr( + // new cuboidal_region_type( + // ""world"", cuboidal_region_shape_type(center, center)))); + } + +public: + + /** + * redirects + */ + + virtual ecell4::Integer num_particles() const + { + return (*ps_).num_particles(); + } + + virtual ecell4::Integer num_particles_exact(const ecell4::Species& sp) const + { + return (*ps_).num_particles_exact(sp); + } + + virtual ecell4::Integer num_particles(const ecell4::Species& sp) const + { + return (*ps_).num_particles(sp); + } + + virtual ecell4::Integer num_molecules(const ecell4::Species& sp) const + { + return (*ps_).num_molecules(sp); + } + + virtual ecell4::Integer num_molecules_exact(const ecell4::Species& sp) const + { + return (*ps_).num_molecules_exact(sp); + } + + virtual ecell4::Integer num_species() const + { + return (*ps_).num_species(); + } + + virtual bool has_species(const ecell4::Species& sp) const + { + return (*ps_).has_species(sp); + } + + virtual std::vector > list_particles() const + { + return (*ps_).list_particles(); + } + + virtual std::vector > + list_particles(const ecell4::Species& sp) const + { + return (*ps_).list_particles(sp); + } + + virtual std::vector > + list_particles_exact(const ecell4::Species& sp) const + { + return (*ps_).list_particles_exact(sp); + } + + std::vector list_species() const + { + return (*ps_).list_species(); + } + + virtual const position_type& edge_lengths() const + { + return (*ps_).edge_lengths(); + } + + virtual void reset(const position_type& lengths) + { + (*ps_).reset(lengths); + } + + position_type cell_sizes() const + { + return (*ps_).cell_sizes(); + } + + matrix_sizes_type matrix_sizes() const + { + return (*ps_).matrix_sizes(); + } + + virtual bool has_particle(particle_id_type const& id) const + { + return (*ps_).has_particle(id); + } + + virtual particle_id_pair get_particle(particle_id_type const& id) const + { + return (*ps_).get_particle(id); + } + + virtual length_type distance( + position_type const& lhs, position_type const& rhs) const + { + return (*ps_).distance(lhs, rhs); + } + + virtual position_type apply_boundary(position_type const& v) const + { + return (*ps_).apply_boundary(v); + } + + virtual const time_type t() const + { + return (*ps_).t(); + } + + virtual void set_t(const time_type& t) + { + (*ps_).set_t(t); + } + + virtual void remove_particle(particle_id_type const& id) + { + (*ps_).remove_particle(id); + } + + virtual position_type periodic_transpose( + position_type const& p0, position_type const& p1) const + { + return (*ps_).periodic_transpose(p0, p1); + } + + std::vector, length_type> > + list_particles_within_radius( + const position_type& pos, const length_type& radius) const + { + return (*ps_).list_particles_within_radius(pos, radius); + } + + std::vector, length_type> > + list_particles_within_radius( + const position_type& pos, const length_type& radius, + const particle_id_type& ignore) const + { + return (*ps_).list_particles_within_radius(pos, radius, ignore); + } + + std::vector, length_type> > + list_particles_within_radius( + const position_type& pos, const length_type& radius, + const particle_id_type& ignore1, const particle_id_type& ignore2) const + { + return (*ps_).list_particles_within_radius(pos, radius, ignore1, ignore2); + } + + /** + * wrappers + */ + + template + T1_ calculate_pair_CoM( + T1_ const& p1, T1_ const& p2, + typename element_type_of::type const& D1, + typename element_type_of::type const& D2) + { + typedef typename element_type_of::type element_type; + + const T1_ p2_trans(periodic_transpose(p2, p1)); + const element_type D12(add(D1, D2)); + const element_type s(divide(D1, D12)), t(divide(D2, D12)); + const T1_ com(add(multiply(p1, t), multiply(p2_trans, s))); + return apply_boundary(com); + } + + particle_id_pair get_particle(particle_id_type const& id, bool& found) const + { + found = (*ps_).has_particle(id); + if (!found) + { + return particle_id_pair(); + } + return get_particle(id); + } + + virtual particle_id_pair_and_distance_list check_overlap(particle_shape_type const& s) const + { + return (*ps_).list_particles_within_radius(s.position(), s.radius()); + } + + virtual particle_id_pair_and_distance_list check_overlap(particle_shape_type const& s, particle_id_type const& ignore) const + { + return (*ps_).list_particles_within_radius(s.position(), s.radius(), ignore); + } + + virtual particle_id_pair_and_distance_list check_overlap(particle_shape_type const& s, particle_id_type const& ignore1, particle_id_type const& ignore2) const + { + return (*ps_).list_particles_within_radius(s.position(), s.radius(), ignore1, ignore2); + } + + particle_id_pair_range get_particles_range() const + { + const particle_space_type::particle_container_type& particles((*ps_).particles()); + return particle_id_pair_range(particles.begin(), particles.end(), particles.size()); + } + + /** + * + */ + + template + length_type distance(T_ const& lhs, position_type const& rhs) const + { + // return (*ps_).distance(lhs, rhs); + return traits_type::distance(lhs, rhs, edge_lengths()); + } + + void clear() + { + // particle_id_generator pidgen_; + // std::shared_ptr rng_; + // std::weak_ptr model_; + ; // do nothing + + // molecule_info_map molecule_info_map_; + // structure_map structure_map_; + // per_species_particle_id_set particle_pool_; + molecule_info_map_.clear(); + structure_map_.clear(); + + (*ps_).reset((*ps_).edge_lengths()); + } + +// virtual position_type +// apply_reflection(const position_type& pos, const position_type& disp) +// { +// return polygon_.apply_reflection(pos, disp, +// (polygon_.get_faces_within_radius(pos, length(disp))).first, +// this->edge_lengths()); +// } + + //XXX: this function is for BD (Multi Domain), with polygon. this reflects + // particle if particle collides with polygon surface. + virtual position_type + apply_structure(const position_type& pos, const position_type& disp) const + { + if(!polygon_) + { + // if there is no polygon face, particle never collides. + // to avoid overhead because of calling apply_structure_rec, + // just skip it and use normal `apply_boundary`. + return this->apply_boundary(pos + disp); + } + return this->apply_structure_rec(pos, disp, boost::none, boost::none); + } + +protected: + + enum class BoundaryAxis : std::uint8_t + { + X_lower = 0, X_upper = 1, + Y_lower = 2, Y_upper = 3, + Z_lower = 4, Z_upper = 5 + }; + + //XXX: this code is for BD (Multi Domain), with polygon. + // To deal with the collision between particle and polygon under the + // Periodic Boundary Condition, it applies PBC and collision in order. + position_type + apply_structure_rec(const position_type& pos, const position_type& disp, + const boost::optional ignore_face, + const boost::optional ignore_boundary) const + { + assert(this->polygon_); + + const auto& edge = edge_lengths(); + + // --------------------------------------------------------------------- + // first, check the particle go across the boundary. + // + // Here we can assume that the particle position is currently inside of + // the boundary. + // + // Also, if particle once go across the boundary, we need to skip it to + // avoid infinite recursion. + + boost::optional collided_boundary = boost::none; + Real tmin_unitcell = std::numeric_limits::infinity(); + for(std::size_t i=0; i<3; ++i) + { + if(std::abs(disp[i]) < std::numeric_limits::epsilon()) + { + continue; // in this direction, it does not move. + } + + if(0 < disp[i]) // upper boundary (edge_lengths) + { + const BoundaryAxis b = static_cast(i * 2 + 1); + if(ignore_boundary && *ignore_boundary == b) + { + continue; + } + const Real tmp = (edge[i] - pos[i]) / disp[i]; + if(tmp < tmin_unitcell) + { + tmin_unitcell = tmp; + collided_boundary = b; + } + } + else // lower boundary (0,0,0) + { + const BoundaryAxis b = static_cast(i * 2); + if(ignore_boundary && *ignore_boundary == b) + { + continue; + } + const Real tmp = (0.0 - pos[i]) / disp[i]; + if(tmp < tmin_unitcell) + { + tmin_unitcell = tmp; + collided_boundary = b; + } + } + } + + const bool test_unitcell = (0.0 <= tmin_unitcell && tmin_unitcell <= 1.0); + const Real dist_to_unit_cell = length(disp) * tmin_unitcell; + + // --------------------------------------------------------------------- + // next, we need to check whether a particle collides with a polygon + + const std::pair>> + test_polygon = intersect_ray(*polygon_, pos, disp, ignore_face); + + // --------------------------------------------------------------------- + // If the particle does not collide neither of them, do nothing special. + + if(!test_unitcell && !test_polygon.first) + { + return pos + disp; + } + + // --------------------------------------------------------------------- + // If the particle collides to a polygon before boundary, reflect the + // displacement. + + if(test_polygon.first && test_polygon.second.first < dist_to_unit_cell) + { + const std::pair, FaceID> + reflected = ::ecell4::egfrd::apply_reflection( + *polygon_, pos, disp, *test_polygon.second.second); + return this->apply_structure_rec(reflected.first.first, + reflected.first.second - reflected.first.first, + reflected.second, boost::none); + } + else if(test_unitcell) + { + assert(0.0 <= tmin_unitcell && tmin_unitcell <= 1.0); + + Real3 next_pos = pos + disp * tmin_unitcell; + const Real3 next_disp = disp * (1.0 - tmin_unitcell); + + switch(*collided_boundary) + { + case BoundaryAxis::X_lower: {next_pos[0] += edge[0]; break;} + case BoundaryAxis::X_upper: {next_pos[0] -= edge[0]; break;} + case BoundaryAxis::Y_lower: {next_pos[1] += edge[1]; break;} + case BoundaryAxis::Y_upper: {next_pos[1] -= edge[1]; break;} + case BoundaryAxis::Z_lower: {next_pos[2] += edge[2]; break;} + case BoundaryAxis::Z_upper: {next_pos[2] -= edge[2]; break;} + defaut: {assert(false);} + } + return this->apply_structure_rec(next_pos, next_disp, boost::none, + collided_boundary); + } + else + { + throw std::logic_error(""never reach here""); + } + } + +protected: + + std::unique_ptr ps_; + + boost::optional polygon_; + +private: + + particle_id_generator pidgen_; + molecule_info_map molecule_info_map_; + structure_map structure_map_; + + /** ecell4::Space + */ + std::shared_ptr rng_; + std::weak_ptr model_; +}; + +} // egfrd +} // ecell4 +#endif /* WORLD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ParticleSimulator.hpp",".hpp","4037","149","#ifndef ECELL4_EGFRD_PARTICLE_SIMULATOR_HPP +#define ECELL4_EGFRD_PARTICLE_SIMULATOR_HPP + +#include ""ReactionRuleInfo.hpp"" +#include ""ReactionRecorder.hpp"" +#include ""ReactionRecord.hpp"" +#include ""VolumeClearer.hpp"" + +#include ""NetworkRulesAdapter.hpp"" +#include ""ReactionRecorderWrapper.hpp"" +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct ParticleSimulatorTraitsBase +{ + typedef Tworld_ world_type; + typedef Real rate_type; + typedef Real time_type; + typedef ecell4::ReactionRule reaction_rule_id_type; + typedef ReactionRuleInfo< + reaction_rule_id_type, + typename world_type::traits_type::species_id_type, + rate_type> reaction_rule_type; + typedef NetworkRulesAdapter network_rules_type; + typedef ReactionRecord reaction_record_type; + typedef ReactionRecorder reaction_recorder_type; + typedef VolumeClearer volume_clearer_type; + + static constexpr Real MINIMAL_SEPARATION_FACTOR = 1.0 + 1e-7; +}; + +template +constexpr Real ParticleSimulatorTraitsBase::MINIMAL_SEPARATION_FACTOR; + +template +class ParticleSimulator + : public ecell4::SimulatorBase< + typename Ttraits_::world_type, + typename Ttraits_::world_type::traits_type::model_type> +{ +public: + + typedef Ttraits_ traits_type; + typedef typename traits_type::world_type world_type; + + typedef typename traits_type::network_rules_type network_rules_type; + typedef typename traits_type::time_type time_type; + typedef typename traits_type::reaction_record_type reaction_record_type; + typedef typename traits_type::reaction_recorder_type reaction_recorder_type; + typedef typename traits_type::volume_clearer_type volume_clearer_type; + + typedef typename world_type::traits_type::rng_type rng_type; + typedef typename world_type::traits_type::model_type model_type; + + typedef ecell4::SimulatorBase base_type; + +public: + + virtual ~ParticleSimulator() {} + + ParticleSimulator( + const std::shared_ptr& world, + const std::shared_ptr& model) + : base_type(world, model), + network_rules_(new network_rules_type(model)), + rrec_(new ReactionRecorderWrapper()), + dt_(0.), paranoiac_(false) + { + ; + } + + ParticleSimulator( + const std::shared_ptr& world) + : base_type(world), + network_rules_(new network_rules_type(this->model())), + rrec_(new ReactionRecorderWrapper()), + dt_(0.), paranoiac_(false) + { + ; + } + + std::shared_ptr const& network_rules() const + { + return network_rules_; + } + + // std::shared_ptr const& reaction_recorder() const + // { + // return rrec_; + // } + + // std::shared_ptr& reaction_recorder() + // { + // return rrec_; + // } + + inline rng_type& rng() const + { + return (*(*base_type::world_).rng().get()); + } + + virtual void set_dt(const Real& dt) + { + std::cerr << ""WARN: set_dt(const Real&) was just ignored."" << std::endl; + dt_ = dt; + } + + virtual time_type dt() const + { + return dt_; //XXX: dt has no mean for egfrd. + } + + bool const& paranoiac() const + { + return paranoiac_; + } + + bool& paranoiac() + { + return paranoiac_; + } + + void set_paranoiac(const bool val) + { + paranoiac_ = val; + } + + virtual void step() = 0; + virtual bool step(const time_type& upto) = 0; + +protected: + std::shared_ptr network_rules_; + std::shared_ptr rrec_; + time_type dt_; + bool paranoiac_; + +}; + +} // egfrd +} // ecell4 +#endif /* PARTICLE_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Shell.hpp",".hpp","2613","114","#ifndef ECELL4_EGFRD_SHELL_HPP +#define ECELL4_EGFRD_SHELL_HPP + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct Shell +{ + typedef Tshape_ shape_type; + typedef Tdid_ domain_id_type; + typedef typename shape_type::position_type position_type; + typedef typename shape_type::length_type length_type; + + Shell(): domain_id_(), shape_() {} + + Shell(domain_id_type const& domain_id, shape_type const& shape) + : domain_id_(domain_id), shape_(shape) {} + + position_type& position() + { + return shape_.position(); + } + + position_type const& position() const + { + return shape_.position(); + } + + shape_type& shape() + { + return shape_; + } + + shape_type const& shape() const + { + return shape_; + } + + domain_id_type const& did() const + { + return domain_id_; + } + + domain_id_type& did() + { + return domain_id_; + } + + bool operator==(Shell const& rhs) const + { + return domain_id_ == rhs.did() && shape_ == rhs.shape(); + } + + bool operator!=(Shell const& rhs) const + { + return !operator==(rhs); + } + +private: + domain_id_type domain_id_; + shape_type shape_; +}; + +template +inline Shell offset( + Shell const& shape, typename Shell::position_type off) +{ + Shell retval(shape); + retval.position() += off; + return retval; +} + +// template +// inline typename Shell::shape_type& shape(Shell& obj) +// { +// return obj.shape(); +// } + +template +inline typename Shell::shape_type const& shape(Shell const& obj) +{ + return obj.shape(); +} + +template +inline std::basic_ostream& operator<<(std::basic_ostream& strm, const Shell& v) +{ + strm << ""Shell("" << v.shape() << "", "" << v.did() << "")""; + return strm; +} +} // egfrd +} // ecell4 + +namespace std { +template +struct hash > +{ + typedef ecell4::egfrd::Shell argument_type; + + std::size_t operator()(argument_type const& val) + { + return hash()(val.shape()) ^ + hash()(val.did()); + } +}; +} // std +#endif /* SHELL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Polygon.hpp",".hpp","6336","221","#ifndef ECELL4_EGFRD_POLYGON_HPP +#define ECELL4_EGFRD_POLYGON_HPP + +#include +#include +#include +#include +#include +#include +#include ""exceptions.hpp"" +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +namespace detail +{ +inline Real3 closest_point(const Real3& pos, const std::array& vertices) +{ + // this implementation is from Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.141-142 + + const Real3 a = vertices[0]; + const Real3 b = vertices[1]; + const Real3 c = vertices[2]; + + const Real3 ab = b - a; + const Real3 ac = c - a; + const Real3 ap = pos - a; + const Real d1 = dot_product(ab, ap); + const Real d2 = dot_product(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) + { + return a; + } + + const Real3 bp = pos - b; + const Real d3 = dot_product(ab, bp); + const Real d4 = dot_product(ac, bp); + if (d3 >= 0.0 && d4 <= d3) + { + return b; + } + + const Real vc = d1*d4 - d3*d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) + { + Real v = d1 / (d1 - d3); + return a + ab * v; + } + + const Real3 cp = pos - c; + const Real d5 = dot_product(ab, cp); + const Real d6 = dot_product(ac, cp); + if (d6 >= 0.0 && d5 <= d6) + { + return c; + } + + const Real vb = d5*d2 - d1*d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) + { + const Real w = d2 / (d2 - d6); + return a + ac * w; + } + + const Real va = d3*d6 - d5*d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) + { + const Real w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return b + (c - b) * w; + } + + const Real denom = 1.0 / (va + vb + vc); + const Real v = vb * denom; + const Real w = vc * denom; + return a + ab * v + ac * w; +} + +inline std::pair +test_intersect_segment_triangle(const Real3& begin, const Real3& end, + const std::array& vertices) +{ + // this implementation is from Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.190-194 + + const Real3 line = begin - end; + const Real3 ab = vertices[1] - vertices[0]; + const Real3 ac = vertices[2] - vertices[0]; + const Real3 normal = cross_product(ab, ac); + + const Real d = dot_product(line, normal); + if(d < 0.0) + { + return std::make_pair(false, Real3(0.,0.,0.)); + } + + const Real3 ap = begin - vertices[0]; + const Real t = dot_product(ap, normal); + if(t < 0.0 || d < t) + { + return std::make_pair(false, Real3(0.,0.,0.)); + } + + const Real3 e = cross_product(line, ap); + Real v = dot_product(ac, e); + if(v < 0. || d < v) + { + return std::make_pair(false, Real3(0.,0.,0.)); + } + Real w = -1.0 * dot_product(ab, e); + if(w < 0. || d < v + w) + { + return std::make_pair(false, Real3(0.,0.,0.)); + } + + const Real ood = 1. / d; + v *= ood; + w *= ood; + const Real u = 1. - v - w; + const Real3 intersect = vertices[0] * u + vertices[1] * v + vertices[2] * w; + + return std::make_pair(true, intersect); +} +} // detail + +inline Real distance_point_to_triangle(const Real3& pos, const Triangle& face) +{ + std::array triangle = face.vertices(); + if(dot_product(pos - face.vertex_at(0), face.normal()) < 0) + { + triangle[0] = face.vertex_at(2); + triangle[1] = face.vertex_at(1); + triangle[2] = face.vertex_at(0); + } + return length(detail::closest_point(pos, triangle) - pos); +} + +inline std::pair +test_intersect_segment_triangle(const Real3& begin, const Real3& end, + const Triangle& face) +{ + const Real3 line = end - begin; + if(dot_product(line, face.normal()) < 0.0) + { + return detail::test_intersect_segment_triangle(begin, end, face.vertices()); + } + else + { + std::array rev; + rev[0] = face.vertex_at(2); + rev[1] = face.vertex_at(1); + rev[2] = face.vertex_at(0); + return detail::test_intersect_segment_triangle(begin, end, rev); + } +} + +inline std::pair, FaceID> +apply_reflection(const Polygon& poly, const Real3& pos, const Real3& disp, + const FaceID intruder_face) +{ + const Real3 stop = pos + disp; + const auto& tri = poly.triangle_at(intruder_face); + + const std::pair test_result = + test_intersect_segment_triangle(pos, stop, tri); + + const Real3 next_stop = + reflect_plane(pos, stop, tri.normal(), tri.vertex_at(0)); + + return std::make_pair(std::make_pair(test_result.second, next_stop), + intruder_face); +} + +inline std::pair>> +intersect_ray(const Polygon& poly, const Real3& pos, const Real3& disp, + const boost::optional ignore_face) +{ + const Real3 stop = pos + disp; + const Real len = length(disp); + + bool collide_face = false; + Real first_collide_dist_sq = len * len; + boost::optional first_collide_face_idx = boost::none; + + const auto intruders = + ignore_face ? poly.list_faces_within_radius(pos, len, *ignore_face) : + poly.list_faces_within_radius(pos, len); + + for(const auto& intruder : intruders) + { + const FaceID& fid = intruder.first.first; + const Triangle& tri = intruder.first.second; + + const std::pair test_result = + test_intersect_segment_triangle(pos, stop, tri); + + if(test_result.first) + { + const Real distsq_to_face = length_sq(test_result.second - pos); + if(distsq_to_face < first_collide_dist_sq) + { + collide_face = true; + first_collide_face_idx = fid; + first_collide_dist_sq = distsq_to_face; + } + } + } + return std::make_pair(collide_face, std::make_pair( + std::sqrt(first_collide_dist_sq), first_collide_face_idx)); +} + +} // egfrd +} // ecell4 +#endif // ECELL4_EGFRD_POLYGON_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/BDPropagator.hpp",".hpp","17337","442","#ifndef ECELL4_EGFRD_BD_PROPAGATOR_HPP +#define ECELL4_EGFRD_BD_PROPAGATOR_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include ""generator.hpp"" +#include ""exceptions.hpp"" +#include ""utils/random.hpp"" +#include ""Logger.hpp"" + +#include ""PotentialField.hpp"" +#include +// using namespace greens_functions; + +namespace ecell4 +{ +namespace egfrd +{ + +template +class BDPropagator +{ +public: + typedef Ttraits_ traits_type; + typedef typename Ttraits_::world_type::particle_container_type particle_container_type; + typedef typename particle_container_type::species_id_type species_id_type; + typedef typename particle_container_type::position_type position_type; + typedef typename particle_container_type::particle_shape_type particle_shape_type; + typedef typename particle_container_type::molecule_info_type molecule_info_type; + typedef typename particle_container_type::length_type length_type; + typedef typename particle_container_type::particle_id_type particle_id_type; + typedef typename particle_container_type::particle_type particle_type; + typedef typename particle_container_type::particle_id_pair particle_id_pair; + typedef std::vector particle_id_vector_type; + typedef typename particle_container_type::particle_id_pair_generator particle_id_pair_generator; + typedef typename particle_container_type::particle_id_pair_and_distance particle_id_pair_and_distance; + typedef typename particle_container_type::particle_id_pair_and_distance_list particle_id_pair_and_distance_list; + typedef typename particle_container_type::structure_type structure_type; + typedef typename traits_type::world_type::traits_type::rng_type rng_type; + typedef typename traits_type::time_type time_type; + typedef typename traits_type::network_rules_type network_rules_type; + typedef typename network_rules_type::reaction_rules reaction_rules; + typedef typename network_rules_type::reaction_rule_type reaction_rule_type; + typedef typename traits_type::reaction_record_type reaction_record_type; + typedef typename traits_type::reaction_recorder_type reaction_recorder_type; + typedef typename traits_type::volume_clearer_type volume_clearer_type; + + typedef std::unordered_map particle_id_position_map_type; + + typedef ecell4::egfrd::PotentialField potential_field_type; + typedef std::unordered_map> potential_field_map_type; + +public: + template + BDPropagator( + particle_container_type& tx, network_rules_type const& rules, + rng_type& rng, time_type dt, int max_retry_count, + reaction_recorder_type* rrec, volume_clearer_type* vc, + Trange_ const& particles, + potential_field_map_type const& potentials = potential_field_map_type()) + : tx_(tx), rules_(rules), rng_(rng), dt_(dt), + max_retry_count_(max_retry_count), rrec_(rrec), vc_(vc), + queue_(), rejected_move_count_(0), + potentials_(potentials) + { + queue_.reserve(ecell4::egfrd::size(particles)); + for(const auto& p : particles) + { + queue_.push_back(p); + } + shuffle(rng, queue_); + } + + bool operator()() + { + if (queue_.empty()) + return false; + + particle_id_type pid(queue_.back()); + queue_.pop_back(); + particle_id_pair pp(tx_.get_particle(pid)); + + LOG_DEBUG((""propagating particle %s"", boost::lexical_cast(pp.first).c_str())); + + try + { + if (attempt_reaction(pp)) + return true; + } + catch (PropagationError const& reason) + { + log_.info(""first-order reaction rejected (reason: %s)"", reason.what()); + ++rejected_move_count_; + return true; + } + + const species_id_type& species_id(pp.second.species()); + const molecule_info_type species(tx_.get_molecule_info(species_id)); + if (species.D == 0.) + return true; + + position_type const displacement = drawR_free(species); + position_type const new_pos = tx_.apply_structure(pp.second.position(), displacement); +// position_type const new_pos = tx_.apply_boundary(reflected); + + // typename potential_field_map_type::const_iterator it = potentials_.find(species_id); + // if (it != potentials_.end()) + // { + // if (!(*it).second->try_move(rng_, pp, new_pos, tx_)) + // { + // return true; + // } + // } + + particle_id_pair particle_to_update( + pp.first, particle_type(species_id, + new_pos, species.radius, + species.D)); + particle_id_pair_and_distance_list overlapped( + tx_.check_overlap(shape(particle_to_update.second), + particle_to_update.first)); + switch (overlapped.size()) + { + case 0: + break; + + case 1: + { + particle_id_pair_and_distance const& closest(overlapped.at(0)); + try + { + if (!attempt_reaction(pp, closest.first)) + { + LOG_DEBUG((""collision with a nonreactive particle %s. move rejected"", boost::lexical_cast(closest.first.first).c_str())); + ++rejected_move_count_; + } + } + catch (PropagationError const& reason) + { + log_.info(""second-order reaction rejected (reason: %s)"", reason.what()); + ++rejected_move_count_; + } + } + /* reject the move even if the reaction has not occurred */ + return true; + + default: + log_.info(""collision involving two or more particles; move rejected""); + ++rejected_move_count_; + return true; + } + if (vc_) + { + if (!(*vc_)(shape(particle_to_update.second), + particle_to_update.first)) + { + log_.info(""propagation move rejected.""); + return true; + } + } + tx_.update_particle(particle_to_update.first, particle_to_update.second); + return true; + } + + std::size_t get_rejected_move_count() const + { + return rejected_move_count_; + } + +private: + position_type drawR_free(molecule_info_type const& species) + { + return tx_.get_structure(species.structure_id)->bd_displacement(std::sqrt(2.0 * species.D * dt_), rng_); + } + + bool attempt_reaction(particle_id_pair const& pp) + { + reaction_rules const& rules(rules_.query_reaction_rule(pp.second.species())); + if (ecell4::egfrd::size(rules) == 0) + { + return false; + } + + const Real rnd(rng_.random() / dt_); + Real prob = 0.; + + for (typename boost::range_const_iterator::type + i(boost::begin(rules)), e(boost::end(rules)); i != e; ++i) + { + reaction_rule_type const& r(*i); + prob += r.k(); + if (prob > rnd) + { + typename reaction_rule_type::species_id_range products( + r.get_products()); + switch (ecell4::egfrd::size(products)) + { + case 0: + remove_particle(pp.first); + break; + + case 1: + { + const molecule_info_type s0(tx_.get_molecule_info(products[0])); + const particle_id_pair new_p( + pp.first, particle_type(products[0], + pp.second.position(), s0.radius, s0.D)); + if (!tx_.no_overlap(shape(new_p.second), new_p.first)) + { + throw PropagationError(""no space""); + } + + if (vc_) + { + if (!(*vc_)(shape(new_p.second), pp.first)) + { + throw PropagationError(""no space""); + } + } + + tx_.update_particle(new_p.first, new_p.second); + + if (rrec_) + { + // (*rrec_)( + // reaction_record_type( + // r.id(), array_gen(new_p.first), pp.first)); + (*rrec_)( + reaction_record_type(r.id(), array_gen(new_p), pp)); + } + } + break; + + case 2: + { + const species_id_type& product_id0(products[0]), + product_id1(products[1]); + const molecule_info_type s0(tx_.get_molecule_info(product_id0)), + s1(tx_.get_molecule_info(product_id1)); + const Real D01(s0.D + s1.D); + const length_type r01(s0.radius + s1.radius); + int i = max_retry_count_; + position_type np0, np1; + + for (;;) + { + if (--i < 0) + { + throw PropagationError(""no space""); + } + + const Real rnd(rng_.random()); + length_type pair_distance( + greens_functions::drawR_gbd_3D(rnd, r01, dt_, D01)); + const position_type m(random_unit_vector() * pair_distance); + np0 = tx_.apply_boundary(pp.second.position() + + m * (s0.D / D01)); + np1 = tx_.apply_boundary(pp.second.position() + - m * (s1.D / D01)); + + const particle_shape_type sphere1(np0, s0.radius); + const particle_shape_type sphere2(np1, s1.radius); + if (tx_.no_overlap(sphere1, pp.first) + && tx_.no_overlap(sphere2, pp.first)) + { + break; + } + } + + if (vc_) + { + if (!(*vc_)(particle_shape_type(np0, s0.radius), pp.first) || !(*vc_)(particle_shape_type(np1, s1.radius), pp.first)) + { + throw PropagationError(""no space""); + } + } + + tx_.remove_particle(pp.first); + const particle_id_pair + npp0(tx_.new_particle(product_id0, np0).first), + npp1(tx_.new_particle(product_id1, np1).first); + + if (rrec_) + { + // (*rrec_)( + // reaction_record_type( + // r.id(), + // array_gen(npp0.first, npp1.first), + // pp.first)); + (*rrec_)(reaction_record_type(r.id(), array_gen(npp0, npp1), pp)); + } + } + break; + default: + throw ::ecell4::NotImplemented(""monomolecular reactions that produce more than two products are not supported""); + } + return true; + } + } + return false; + } + + bool attempt_reaction(particle_id_pair const& pp0, particle_id_pair const& pp1) + { + reaction_rules const& rules(rules_.query_reaction_rule(pp0.second.species(), pp1.second.species())); + if (ecell4::egfrd::size(rules) == 0) + { + return false; + } + + const molecule_info_type s0(tx_.get_molecule_info(pp0.second.species())), + s1(tx_.get_molecule_info(pp1.second.species())); + const length_type r01(s0.radius + s1.radius); + + const Real rnd(rng_.random()); + Real prob = 0; + + for (typename boost::range_const_iterator::type + i(boost::begin(rules)), e(boost::end(rules)); i != e; ++i) + { + reaction_rule_type const& r(*i); + const Real p(r.k() * dt_ / ((greens_functions::I_bd_3D(r01, dt_, s0.D) + greens_functions::I_bd_3D(r01, dt_, s1.D)) * 4.0 * M_PI)); + BOOST_ASSERT(p >= 0.); + prob += p; + if (prob >= 1.) + { + throw PropagationError( + ""invalid acceptance ratio ("" + + boost::lexical_cast(p) + + "") for reaction rate "" + + boost::lexical_cast(r.k()) + + "".""); + } + if (prob > rnd) + { + LOG_DEBUG((""fire reaction"")); + const typename reaction_rule_type::species_id_range products( + r.get_products()); + + switch (ecell4::egfrd::size(products)) + { + case 1: + { + const species_id_type product(products[0]); + const molecule_info_type sp(tx_.get_molecule_info(product)); + + const position_type new_pos( + tx_.apply_boundary( + divide( + add(multiply(pp0.second.position(), s1.D), + multiply(tx_.periodic_transpose( + pp1.second.position(), + pp0.second.position()), s0.D)), + (s0.D + s1.D)))); + if (!tx_.no_overlap( + particle_shape_type(new_pos, sp.radius), + pp0.first, pp1.first)) + { + throw PropagationError(""no space""); + } + + if (vc_) + { + if (!(*vc_)( + particle_shape_type(new_pos, sp.radius), + pp0.first, pp1.first)) + { + throw PropagationError(""no space""); + } + } + + remove_particle(pp0.first); + remove_particle(pp1.first); + particle_id_pair npp(tx_.new_particle(product, new_pos).first); + if (rrec_) + { + // (*rrec_)( + // reaction_record_type( + // r.id(), array_gen(npp.first), pp0.first, pp1.first)); + (*rrec_)(reaction_record_type(r.id(), array_gen(npp), pp0, pp1)); + } + break; + } + case 0: + remove_particle(pp0.first); + remove_particle(pp1.first); + break; + default: + throw ::ecell4::NotImplemented(""bimolecular reactions that produce more than one product are not supported""); + } + + return true; + } + } + return false; + } + + void remove_particle(particle_id_type const& pid) + { + LOG_DEBUG((""remove particle %s"", boost::lexical_cast(pid).c_str())); + tx_.remove_particle(pid); + typename particle_id_vector_type::iterator i( + std::find(queue_.begin(), queue_.end(), pid)); + if (queue_.end() != i) + queue_.erase(i); + } + +private: + position_type random_unit_vector() + { + position_type v(rng_.random() - 0.5, rng_.random() - 0.5, rng_.random() - 0.5); + return v / length(v); + } + +private: + particle_container_type& tx_; + network_rules_type const& rules_; + rng_type& rng_; + Real const dt_; + int const max_retry_count_; + reaction_recorder_type* const rrec_; + volume_clearer_type* const vc_; + particle_id_vector_type queue_; + int rejected_move_count_; + potential_field_map_type const& potentials_; + static Logger& log_; +}; + +template +Logger& BDPropagator::log_(Logger::get_logger(""ecell.BDPropagator"")); + +} // egfrd +} // ecell4 +#endif /* BD_PROPAGATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Single.hpp",".hpp","1187","52","#ifndef ECELL4_EGFRD_SINGLE_HPP +#define ECELL4_EGFRD_SINGLE_HPP + +#include +#include ""ShapedDomain.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ +template +class Single: public ShapedDomain +{ +public: + typedef ShapedDomain base_type; + typedef Ttraits_ traits_type; + typedef typename traits_type::world_type::length_type length_type; + typedef typename traits_type::world_type::traits_type::position_type position_type; + typedef typename traits_type::world_type::particle_id_pair particle_id_pair; + typedef typename traits_type::domain_id_type identifier_type; + typedef typename traits_type::world_type::traits_type::D_type D_type; + +public: + virtual ~Single() {} + + Single(identifier_type const& id, + particle_id_pair const& particle) + : base_type(id), particle_(particle) {} + + particle_id_pair const& particle() const + { + return particle_; + } + + particle_id_pair& particle() + { + return particle_; + } + + D_type const& D() const + { + return particle_.second.D(); + } + +protected: + particle_id_pair particle_; +}; + +} // egfrd +} // ecell4 +#endif /* SINGLE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/BDSimulator.hpp",".hpp","9651","305","#ifndef ECELL4_EGFRD_BD_SIMULATOR_HPP +#define ECELL4_EGFRD_BD_SIMULATOR_HPP + +#include +#include + +#include ""BDPropagator.hpp"" +#include ""World.hpp"" +#include ""ParticleSimulator.hpp"" +#include ""utils/pair.hpp"" + +#include ""PotentialField.hpp"" + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct BDSimulatorTraitsBase: public ParticleSimulatorTraitsBase +{ +}; + +template +class BDSimulator: public ParticleSimulator +{ +public: + + typedef Ttraits_ traits_type; + typedef ParticleSimulator base_type; + + typedef typename base_type::model_type model_type; + + typedef typename traits_type::world_type world_type; + typedef typename world_type::traits_type::rng_type rng_type; + typedef typename world_type::species_id_type species_id_type; + // typedef typename world_type::species_type species_type; + typedef typename world_type::molecule_info_type molecule_info_type; + typedef typename world_type::particle_shape_type particle_shape_type; + typedef typename world_type::particle_id_pair particle_id_pair; + typedef typename world_type::particle_type particle_type; + typedef typename world_type::particle_id_type particle_id_type; + typedef typename world_type::traits_type::position_type position_type; + typedef typename traits_type::time_type time_type; + typedef typename traits_type::network_rules_type network_rules_type; + typedef typename traits_type::reaction_rule_type reaction_rule_type; + typedef typename traits_type::rate_type rate_type; + typedef typename traits_type::reaction_record_type reaction_record_type; + typedef typename traits_type::reaction_recorder_type reaction_recorder_type; + typedef typename ReactionRecorderWrapper::reaction_info_type reaction_info_type; + + typedef typename world_type::particle_container_type particle_container_type; + typedef ecell4::egfrd::PotentialField potential_field_type; + typedef std::unordered_map> potential_field_map_type; + +public: + + Real const& dt_factor() + { + return dt_factor_; + } + + virtual ~BDSimulator() {} + + BDSimulator( + const std::shared_ptr& world, + const std::shared_ptr& ecell4_model, + Real bd_dt_factor = 1.0, + int dissociation_retry_moves = 1) + : base_type(world, ecell4_model), + dt_factor_(bd_dt_factor), + num_retries_(dissociation_retry_moves) + { + calculate_dt(); + } + + BDSimulator( + const std::shared_ptr& world, + Real bd_dt_factor = 1.0, + int dissociation_retry_moves = 1) + : base_type(world), + dt_factor_(bd_dt_factor), + num_retries_(dissociation_retry_moves) + { + calculate_dt(); + } + + virtual void initialize() + { + ; + } + + virtual void calculate_dt() + { + set_dt(dt_factor_ * determine_dt()); + LOG_DEBUG((""dt=%f"", base_type::dt_)); + } + + virtual void set_dt(const Real& dt) + { + base_type::dt_ = dt; + } + + virtual void step() + { + _step(base_type::dt()); + } + + void add_potential(const ecell4::Species& sp, const Real& radius) + { + std::pair retval + = potentials_.insert(typename potential_field_map_type::value_type(sp, std::shared_ptr(new ecell4::egfrd::LeashPotentialField(radius)))); + if (!retval.second) + { + throw ecell4::AlreadyExists(""never reach here.""); + } + } + + void add_potential(const ecell4::Species& sp, const std::shared_ptr& shape) + { + std::pair retval + = potentials_.insert(typename potential_field_map_type::value_type(sp, std::shared_ptr(new ecell4::egfrd::ShapedHardbodyPotentialField(shape)))); + if (!retval.second) + { + throw ecell4::AlreadyExists(""never reach here.""); + } + } + + void add_potential(const ecell4::Species& sp, const std::shared_ptr& shape, const Real& threshold) + { + std::pair retval + = potentials_.insert(typename potential_field_map_type::value_type(sp, std::shared_ptr(new ecell4::egfrd::ShapedDiscretePotentialField(shape, threshold)))); + if (!retval.second) + { + throw ecell4::AlreadyExists(""never reach here.""); + } + } + + virtual bool step(const time_type& upto) + { + time_type const lt(upto - base_type::t()); + if (lt <= 0.0) + { + return false; + } + if (base_type::dt() < lt) + { + _step(base_type::dt()); + } + else + { + _step(lt); + base_type::set_t(upto); + } + return true; + } + + Real determine_dt() + { + Real prob = 0.0; + for(reaction_rule_type const& rr: + (*base_type::network_rules_).zeroth_order_reaction_rules()) + { + prob += rr.k(); + } + prob *= (*base_type::world_).volume(); + + if (prob == 0.0 && (*base_type::world_).num_particles() == 0) + { + return std::numeric_limits::infinity(); + } + + Real D_max(0.0), radius_min(std::numeric_limits::max()); + + for(molecule_info_type info: + (*base_type::world_).get_molecule_info_range()) + { + if (D_max < info.D) + { + D_max = info.D; + } + if (radius_min > info.radius) + { + radius_min = info.radius; + } + } + const Real dt(gsl_pow_2(radius_min * 2) / (D_max * 2)); + return (prob == 0.0 ? dt : std::min(dt, 1.0 / prob)); + } + + virtual bool check_reaction() const + { + return last_reactions().size() > 0; + } + + std::vector > last_reactions() const + { + return (*dynamic_cast*>( + base_type::rrec_.get())).last_reactions(); + } + +protected: + + void _step(time_type dt) + { + { + BDPropagator propagator( + *base_type::world_, + *base_type::network_rules_, + base_type::rng(), + dt, num_retries_, + base_type::rrec_.get(), 0, + make_select_first_range(base_type::world_-> + get_particles_range()), + potentials_); + while (propagator()); + } + + try + { + attempt_zeroth_order_reaction(dt); + } + catch (NoSpace const&) + { + LOG_DEBUG((""birth reaction rejected."")); + // ++rejected_moves_; + } + + LOG_DEBUG((""%d: t=%lg, dt=%lg"", base_type::num_steps_, + base_type::t(), dt)); + + ++base_type::num_steps_; + base_type::set_t(base_type::t() + dt); + } + + bool attempt_zeroth_order_reaction(time_type const dt) + { + typename network_rules_type::reaction_rules const + rules((*base_type::network_rules_).zeroth_order_reaction_rules()); + if (ecell4::egfrd::size(rules) == 0) + return false; + + const Real rnd( + base_type::rng().random() / (dt * (*base_type::world_).volume())); + Real prob = 0.0; + + for(reaction_rule_type const& rr: rules) + { + prob += rr.k(); + if (prob > rnd) + { + typename reaction_rule_type::species_id_range products( + rr.get_products()); + BOOST_ASSERT(ecell4::egfrd::size(products) == 1); + const molecule_info_type minfo( + (*base_type::world_).get_molecule_info(products[0])); + + //XXX: A cuboidal region is expected here. + const position_type& edge_lengths((*base_type::world_).edge_lengths()); + const position_type new_pos( + base_type::rng().uniform(0, edge_lengths[0]), + base_type::rng().uniform(0, edge_lengths[1]), + base_type::rng().uniform(0, edge_lengths[2])); + + const particle_shape_type new_particle(new_pos, minfo.radius); + if (!(*base_type::world_).no_overlap(new_particle)) + { + LOG_INFO((""no space for product particle."")); + throw NoSpace(); + } + + particle_id_pair pp( + (*base_type::world_).new_particle(products[0], new_pos).first); + + if (base_type::rrec_) + { + (*base_type::rrec_)( + reaction_record_type(rr.id(), array_gen(pp))); + } + return true; + } + } + return false; + } + +private: + + Real const dt_factor_; + int const num_retries_; + Real R_; + static Logger& log_; + + potential_field_map_type potentials_; +}; + +template +Logger& BDSimulator::log_(Logger::get_logger(""BDSimulator"")); + +} // egfrd; +} // ecell4 +#endif /* BD_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ReactionRecorder.hpp",".hpp","393","23","#ifndef ECELL4_EGFRD_REACTION_RECORDER_HPP +#define ECELL4_EGFRD_REACTION_RECORDER_HPP + +namespace ecell4 +{ +namespace egfrd +{ +template +class ReactionRecorder +{ +public: + typedef Trr_ reaction_record_type; + +public: + virtual ~ReactionRecorder() {} + + virtual void operator()(reaction_record_type const& rec) = 0; +}; + +} // egfrd +} // ecell4 +#endif /* REACTION_RECORDER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/EGFRDSimulator.hpp",".hpp","158445","4263","#ifndef ECELL4_EGFRD_EGFRDSIMULATOR_HPP +#define ECELL4_EGFRD_EGFRDSIMULATOR_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include ""utils/array_helper.hpp"" +#include ""utils/collection_contains.hpp"" +#include ""utils/pointer_as_ref.hpp"" +#include ""utils/pair.hpp"" +#include ""utils/math.hpp"" +#include ""utils/stringizer.hpp"" +#include ""ShellID.hpp"" +#include ""DomainID.hpp"" +#include ""Shell.hpp"" +//#include ""EventScheduler.hpp"" +#include ""ParticleSimulator.hpp"" +#include ""MatrixSpace.hpp"" +#include ""AnalyticalSingle.hpp"" +#include ""AnalyticalPair.hpp"" +#include ""Multi.hpp"" + +#include +#include +#include +#include +#include +#include +// using namespace greens_functions; + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct EGFRDSimulatorTraitsBase: public ParticleSimulatorTraitsBase +{ + typedef ParticleSimulatorTraitsBase base_type; + typedef Tworld_ world_type; + + typedef ShellID shell_id_type; + typedef DomainID domain_id_type; + typedef ecell4::SerialIDGenerator shell_id_generator; + typedef ecell4::SerialIDGenerator domain_id_generator; + typedef Domain domain_type; + typedef std::pair > domain_id_pair; + typedef ecell4::EventScheduler event_scheduler_type; // base_type::time_type == ecell4::Real + // typedef EventScheduler event_scheduler_type; + + typedef typename event_scheduler_type::identifier_type event_id_type; + typedef typename event_scheduler_type::value_type event_id_pair_type; + typedef ecell4::Event event_type; + + template + struct shell_generator + { + typedef Shell type; + }; + + static constexpr Real SAFETY = 1.0 + 1e-5; + static constexpr Real SINGLE_SHELL_FACTOR = 0.1; + static constexpr Real DEFAULT_DT_FACTOR = 1e-5; + static constexpr Real CUTOFF_FACTOR = 5.6; +}; + +template +constexpr Real EGFRDSimulatorTraitsBase::SAFETY; +template +constexpr Real EGFRDSimulatorTraitsBase::SINGLE_SHELL_FACTOR; +template +constexpr Real EGFRDSimulatorTraitsBase::DEFAULT_DT_FACTOR; +template +constexpr Real EGFRDSimulatorTraitsBase::CUTOFF_FACTOR; + +namespace detail { + +template +struct get_greens_function {}; + +template<> +struct get_greens_function +{ + typedef greens_functions::GreensFunction3DAbsSym type; +}; + +template<> +struct get_greens_function +{ + typedef greens_functions::GreensFunction3DAbsSym type; +}; + +template +struct get_pair_greens_function {}; + +template<> +struct get_pair_greens_function +{ + typedef greens_functions::GreensFunction3DRadAbs iv_type; + typedef greens_functions::GreensFunction3DAbsSym com_type; +}; + +template<> +struct get_pair_greens_function +{ + typedef greens_functions::GreensFunction3DRadAbs iv_type; + typedef greens_functions::GreensFunction3DAbsSym com_type; +}; + +} // namespace detail + +template +class EGFRDSimulator; + +template +struct ImmutativeDomainVisitor +{ + typedef typename EGFRDSimulator::multi_type multi_type; + typedef typename EGFRDSimulator::spherical_single_type spherical_single_type; + typedef typename EGFRDSimulator::cylindrical_single_type cylindrical_single_type; + typedef typename EGFRDSimulator::spherical_pair_type spherical_pair_type; + typedef typename EGFRDSimulator::cylindrical_pair_type cylindrical_pair_type; + + virtual ~ImmutativeDomainVisitor() {} + + virtual void operator()(multi_type const&) const = 0; + + virtual void operator()(spherical_single_type const&) const = 0; + + virtual void operator()(cylindrical_single_type const&) const = 0; + + virtual void operator()(spherical_pair_type const&) const = 0; + + virtual void operator()(cylindrical_pair_type const&) const = 0; +}; + +template +struct MutativeDomainVisitor +{ + typedef typename EGFRDSimulator::multi_type multi_type; + typedef typename EGFRDSimulator::spherical_single_type spherical_single_type; + typedef typename EGFRDSimulator::cylindrical_single_type cylindrical_single_type; + typedef typename EGFRDSimulator::spherical_pair_type spherical_pair_type; + typedef typename EGFRDSimulator::cylindrical_pair_type cylindrical_pair_type; + + virtual ~MutativeDomainVisitor() {} + + virtual void operator()(multi_type&) const = 0; + + virtual void operator()(spherical_single_type&) const = 0; + + virtual void operator()(cylindrical_single_type&) const = 0; + + virtual void operator()(spherical_pair_type&) const = 0; + + virtual void operator()(cylindrical_pair_type&) const = 0; +}; + + +#define CHECK(expr) \ + do \ + { \ + if (!(expr)) { retval = false; LOG_DEBUG((""checking [%s] failed"", #expr)); } \ + } while (0) + +template +class EGFRDSimulator: public ParticleSimulator +{ +public: + typedef Ttraits_ traits_type; + typedef ParticleSimulator base_type; + + typedef typename base_type::model_type model_type; + + typedef typename traits_type::world_type world_type; + typedef typename traits_type::domain_id_type domain_id_type; + typedef typename traits_type::shell_id_type shell_id_type; + typedef typename traits_type::template shell_generator::type spherical_shell_type; + typedef typename traits_type::template shell_generator::type cylindrical_shell_type; + typedef typename traits_type::domain_type domain_type; + typedef typename traits_type::domain_id_pair domain_id_pair; + typedef typename traits_type::time_type time_type; + typedef typename traits_type::shell_id_generator shell_id_generator; + typedef typename traits_type::domain_id_generator domain_id_generator; + typedef typename traits_type::network_rules_type network_rules_type; + typedef typename traits_type::reaction_record_type reaction_record_type; + typedef typename traits_type::reaction_recorder_type reaction_recorder_type; + typedef typename traits_type::event_scheduler_type event_scheduler_type; + typedef typename traits_type::event_type event_type; + typedef typename traits_type::event_id_type event_id_type; + typedef typename traits_type::event_id_pair_type event_id_pair_type; + + typedef typename world_type::traits_type::length_type length_type; + typedef typename world_type::traits_type::position_type position_type; + typedef typename world_type::traits_type::rng_type rng_type; + typedef typename world_type::traits_type::particle_type particle_type; + typedef typename world_type::traits_type::D_type D_type; + typedef typename world_type::traits_type::molecule_info_type molecule_info_type; + typedef typename world_type::traits_type::species_id_type species_id_type; + typedef typename world_type::traits_type::structure_type structure_type; + typedef typename world_type::particle_shape_type particle_shape_type; + typedef typename world_type::traits_type::particle_id_type particle_id_type; + typedef typename world_type::particle_id_pair particle_id_pair; + typedef typename world_type::particle_id_pair_and_distance particle_id_pair_and_distance; + typedef typename world_type::particle_id_pair_and_distance_list particle_id_pair_and_distance_list; + + typedef std::pair spherical_shell_id_pair; + typedef std::pair cylindrical_shell_id_pair; + + + typedef typename world_type::traits_type::particle_simulation_structure_type + particle_simulation_structure_type; + // typedef typename world_type::traits_type::spherical_surface_type + // spherical_surface_type; + // typedef typename world_type::traits_type::cylindrical_surface_type + // cylindrical_surface_type; + // typedef typename world_type::traits_type::planar_surface_type planar_surface_type; + typedef typename world_type::traits_type::cuboidal_region_type cuboidal_region_type; + + typedef typename ReactionRecorderWrapper::reaction_info_type reaction_info_type; + + typedef Single single_type; + typedef Pair pair_type; + typedef Multi multi_type; + typedef ShapedDomain shaped_domain_type; + typedef AnalyticalSingle spherical_single_type; + typedef AnalyticalSingle cylindrical_single_type; + typedef AnalyticalPair spherical_pair_type; + typedef AnalyticalPair cylindrical_pair_type; + + typedef boost::variant shell_variant_type; + + enum domain_kind + { + NONE = 0, + SPHERICAL_SINGLE, + CYLINDRICAL_SINGLE, + SPHERICAL_PAIR, + CYLINDRICAL_PAIR, + MULTI, + NUM_DOMAIN_KINDS + }; + + enum single_event_kind + { + SINGLE_EVENT_REACTION, + SINGLE_EVENT_ESCAPE, + NUM_SINGLE_EVENT_KINDS + }; + + enum pair_event_kind + { + PAIR_EVENT_SINGLE_REACTION_0, + PAIR_EVENT_SINGLE_REACTION_1, + PAIR_EVENT_COM_ESCAPE, + PAIR_EVENT_IV_UNDETERMINED, + PAIR_EVENT_IV_ESCAPE, + PAIR_EVENT_IV_REACTION, + NUM_PAIR_EVENT_KINDS + }; + +protected: + typedef boost::fusion::map< + boost::fusion::pair*>, + boost::fusion::pair*> > + shell_matrix_map_type; + typedef typename boost::remove_pointer< + typename boost::fusion::result_of::value_at_key< + shell_matrix_map_type, + spherical_shell_type>::type>::type + spherical_shell_matrix_type; + typedef typename boost::remove_pointer< + typename boost::fusion::result_of::value_at_key< + shell_matrix_map_type, + cylindrical_shell_type>::type>::type + cylindrical_shell_matrix_type; + typedef std::unordered_map> domain_map; + typedef typename network_rules_type::reaction_rules reaction_rules; + typedef typename network_rules_type::reaction_rule_type reaction_rule_type; + typedef typename traits_type::rate_type rate_type; + + class birth_event: public event_type + { + public: + birth_event(time_type time, const reaction_rule_type& rr) + : event_type(time), rr_(rr) + { + ; + } + + virtual ~birth_event() {} + + const reaction_rule_type& reaction_rule() const + { + return rr_; + } + + protected: + reaction_rule_type rr_; + }; + + struct domain_event_base: public event_type + { + domain_event_base(time_type time): event_type(time) {} + + virtual domain_type& domain() const = 0; + }; + + template + class domain_event: public domain_event_base + { + public: + typedef domain_event_base base_type; + typedef Tdomain_ domain_type; + typedef TeventKind_ event_kind_type; + + public: + virtual domain_type& domain() const { return domain_; } + + virtual ~domain_event() {} + + event_kind_type kind() const { return kind_; } + + domain_event(time_type time, + domain_type& domain, + event_kind_type kind) + : base_type(time), domain_(domain), kind_(kind) {} + + private: + domain_type& domain_; + event_kind_type kind_; + }; + + typedef domain_event single_event; + typedef domain_event pair_event; + + class multi_event: public domain_event_base + { + public: + typedef domain_event_base base_type; + typedef multi_type domain_type; + + public: + virtual domain_type& domain() const { return domain_; } + + virtual ~multi_event() {} + + multi_event(time_type time, + domain_type& domain) + : base_type(time), domain_(domain) {} + + private: + domain_type& domain_; + }; + + struct intruder_collector + { + intruder_collector(world_type const& world, + particle_shape_type const& cmp, + domain_id_type const& ignore) + : world(world), cmp(cmp), ignore(ignore), + closest(domain_id_type(), + std::numeric_limits::infinity()) {} + + template + void operator()(Titer const& i, position_type const& off) + { + domain_id_type const& did((*i).second.did()); + if (did == ignore) + return; + + length_type const distance( + world.distance( + shape(offset((*i).second, off)), cmp.position())); + if (distance > cmp.radius()) + { + if (distance < closest.second) + { + closest.first = did; + closest.second = distance; + } + } + else + { + if (!intruders.container()) + { + intruders.container().set(new std::vector()); + } + intruders.push_no_duplicate(did); + } + } + + world_type const& world; + particle_shape_type cmp; + domain_id_type ignore; + std::pair closest; + sorted_list, + std::less, + pointer_as_ref > > intruders; + }; + + struct no_filter + { + bool operator()(domain_id_type const&) const { return true; } + }; + + struct one_id_filter + { + bool operator()(domain_id_type const& did) const { return did != ignore; } + one_id_filter(domain_id_type const& did): ignore(did) {} + + domain_id_type const ignore; + }; + + template + struct domain_collector + { + typedef TfilterFn_ filter_function; + + domain_collector(world_type const& world, + particle_shape_type const& cmp, + filter_function const& filter) + : world(world), cmp(cmp), filter(filter) {} + + template + void operator()(Titer const& i, position_type const& off) + + { + domain_id_type const& did((*i).second.did()); + if (!filter(did)) + return; + + length_type const distance(world.distance(shape(offset((*i).second, off)), cmp.position())); + if (distance < cmp.radius()) + { + if (!neighbors.container()) + { + neighbors.container().set(new std::vector()); + } + neighbors.push_no_duplicate(did); + } + } + + world_type const& world; + particle_shape_type cmp; + filter_function const& filter; + + std::pair closest; + sorted_list, + std::less, + pointer_as_ref > > neighbors; + }; + + template + struct closest_object_finder + { + typedef TdidSet_ domain_id_set; + + closest_object_finder(world_type const& world, + position_type const& cmp, + domain_id_set const& ignore) + : world(world), cmp(cmp), ignore(ignore), + closest(domain_id_type(), + std::numeric_limits::infinity()) {} + + template + void operator()(Titer const& i, position_type const& off) + { + domain_id_type const& did((*i).second.did()); + if (collection_contains(ignore, did)) + return; + + length_type const distance(world.distance(shape(offset((*i).second, off)), cmp)); + if (distance < closest.second) + { + closest.first = did; + closest.second = distance; + } + } + + world_type const& world; + position_type cmp; + domain_id_set const& ignore; + std::pair closest; + }; + + template + struct shell_collector_applier + { + typedef Tcol_ collector_type; + + shell_collector_applier(collector_type& col, + position_type const& pos) + : col_(col), pos_(pos) {} + + template + void operator()(T const& smat) const + { + world_type::traits_type::each_neighbor(*smat.second, col_, pos_); + } + + private: + collector_type& col_; + position_type pos_; + }; + + template + struct domain_shell_map_builder + { + typedef Tmap_ domain_shell_association; + domain_shell_map_builder(world_type const& world, + domain_shell_association& did_map) + : world_(world), did_map_(did_map) {} + + template + void operator()(T const& smat) const + { + BOOST_ASSERT(world_.edge_lengths() == (*smat.second).edge_lengths()); + for(typename boost::remove_pointer::type::value_type pair : *smat.second) + { + did_map_[pair.second.did()].insert(pair.first); + } + } + + private: + world_type const& world_; + domain_shell_association& did_map_; + }; + + template + struct shell_id_collector + { + shell_id_collector(Tset_& shell_ids) + : shell_ids_(shell_ids) + {} + + // type of smat is `MatrixSpace*`. + template + void operator()(T const& smat) const + { + for(const auto& sids : *smat.second) + { + this->shell_ids_.insert(sids.first); + } + } + + private: + // Tset is normally a std::set. + Tset_& shell_ids_; + }; + + struct shell_finder + { + shell_finder(shell_id_type const& id, shell_variant_type& result) + : id(id), result(result) {} + + template + void operator()(T const& smat) const + { + typename boost::remove_pointer::type::const_iterator i((*smat.second).find(id)); + if (i != (*smat.second).end()) + { + result = (*i).second; + } + } + + shell_id_type id; + shell_variant_type& result; + }; + + struct draw_on_com_escape + { + position_type draw_com(spherical_pair_type const& domain, + time_type dt) const + { + return add( + domain.shell().second.position(), + normalize( + create_vector( + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.)), + domain.a_R())); + //XXX: ERROR!!! Use rng_.direction3d + } + + position_type draw_iv(spherical_pair_type const& domain, + time_type dt, position_type const& old_iv) const + { + std::unique_ptr const gf( + choose_pair_greens_function(domain, dt)); + length_type const r(draw_r( + rng_, *gf, dt, domain.a_r(), domain.sigma())); + length_type const theta(draw_theta(rng_, *gf, dt, r)); + return adjust_iv_with_old_iv( + spherical_to_cartesian( + position_type(r, theta, rng_.uniform(0., 1.) * 2 * M_PI)), + old_iv); + } + + position_type draw_com(cylindrical_pair_type const& domain, + time_type dt) const + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // boost::shared_ptr const _structure( + // world_.get_structure( + // world_.find_molecule_info( + // domain.particles()[0].second.sid()) + // .structure_id)); + + // cylindrical_surface_type const* const structure( + // dynamic_cast(_structure.get())); + + // return add( + // domain.shell().second.position(), + // multiply(structure->shape().unit_z(), domain.a_R())); + } + + position_type draw_iv(cylindrical_pair_type const& domain, + time_type dt, position_type const& old_iv) const + { + BOOST_ASSERT(ecell4::egfrd::size(domain.reactions()) == 1); + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // length_type const r( + // draw_r(rng_, greens_functions::GreensFunction3DRadAbs(domain.D_tot(), + // domain.reactions()[0].k(), domain.r0(), + // domain.sigma(), domain.a_r()), + // dt, domain.a_r(), domain.sigma())); + // return multiply(normalize(old_iv), r); + } + + draw_on_com_escape(rng_type& rng, world_type const& world) + : rng_(rng), world_(world) {} + + rng_type& rng_; + world_type const& world_; + }; + + // struct draw_on_single_reaction + // { + // position_type draw_com(spherical_pair_type const& domain, + // time_type dt) const + // { + // return add( + // domain.shell().second.position(), + // draw_r(rng_, + // greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + // dt, domain.a_R())); + + // } + + // position_type draw_iv(spherical_pair_type const& domain, + // time_type dt, position_type const& old_iv) const + // { + // std::unique_ptr const gf( + // choose_pair_greens_function(domain, dt)); + // length_type const r(draw_r( + // rng_, *gf, dt, domain.a_r(), domain.sigma())); + // length_type const theta(draw_theta(rng_, *gf, dt, r)); + // return adjust_iv_with_old_iv( + // spherical_to_cartesian( + // position_type(r, theta, rng_.uniform(0., 1.) * 2 * M_PI)), + // old_iv); + // } + + // position_type draw_com(cylindrical_pair_type const& domain, + // time_type dt) const + // { + // std::shared_ptr const _structure( + // world_.find_molecule_info( + // domain.particles()[0].second.sid()) + // .structure_id); + // + // cylindrical_surface_type const* const structure( + // dynamic_cast(_structure.get())); + + // BOOST_ASSERT(structure); + + // return add( + // domain.shell().second.position(), + // multiply(structure->shape().unit_z(), domain.a_R())); + // } + + // position_type draw_iv(cylindrical_pair_type const& domain, + // time_type dt, position_type const& old_iv) const + // { + // BOOST_ASSERT(::size(domain.reactions()) == 1); + // length_type const r( + // draw_r(rng_, greens_functions::GreensFunction3DRadAbs(domain.D_tot(), + // domain.reactions()[0].k(), domain.r0(), + // domain.sigma(), domain().a_r()), + // dt, domain.a_r(), domain.sigma())); + // BOOST_ASSERT(r > domain.sigma() && r <= domain.a_r()); + // return multiply(normalize(old_iv), r); + // } + + // draw_on_single_reaction(rng_type& rng, world_type const& world) + // : rng_(rng), world_(world) {} + + // rng_type& rng_; + // world_type const& world_; + // }; + + struct draw_on_iv_escape + { + position_type draw_com(spherical_pair_type const& domain, + time_type dt) + { + return add( + domain.shell().second.position(), + normalize( + create_vector( + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.)), + draw_r( + rng_, + greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + dt, domain.a_R()))); + } + + position_type draw_iv(spherical_pair_type const& domain, + time_type dt, position_type const& old_iv) + { + std::unique_ptr const gf( + choose_pair_greens_function(domain, dt)); + length_type const r(domain.a_r()); + length_type const theta(draw_theta(rng_, *gf, dt, r)); + return adjust_iv_with_old_iv( + spherical_to_cartesian( + position_type(r, theta, rng_.uniform(0., 1.) * 2 * M_PI)), + old_iv); + } + + position_type draw_com(cylindrical_pair_type const& domain, + time_type dt) + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // boost::shared_ptr const _structure( + // world_.get_structure( + // world_.find_molecule_info( + // domain.particles()[0].second.sid()) + // .structure_id)); + + // cylindrical_surface_type const* const structure( + // dynamic_cast(_structure.get())); + + // BOOST_ASSERT(structure); + + // length_type const r_R(draw_r( + // rng_, + // greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + // dt, domain.a_R())); + // return add( + // domain.shell().second.position(), + // multiply(structure->shape().unit_z(), r_R)); + } + + position_type draw_iv(cylindrical_pair_type const& domain, + time_type dt, position_type const& old_iv) + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // return multiply(normalize(old_iv), domain.a_r()); + } + + draw_on_iv_escape(rng_type& rng, world_type const& world) + : rng_(rng), world_(world) {} + + rng_type& rng_; + world_type const& world_; + }; + + struct draw_on_iv_reaction + { + position_type draw_com(spherical_pair_type const& domain, + time_type dt) + { + return add( + domain.shell().second.position(), + normalize( + create_vector( + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.)), + draw_r( + rng_, + greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + dt, domain.a_R()))); + } + + position_type draw_iv(spherical_pair_type const& domain, + time_type dt, position_type const& old_iv) + { + std::unique_ptr const gf( + choose_pair_greens_function(domain, dt)); + length_type const r(domain.sigma()); + length_type const theta(draw_theta(rng_, *gf, dt, r)); + return adjust_iv_with_old_iv( + spherical_to_cartesian( + position_type(r, theta, rng_.uniform(0., 1.) * 2 * M_PI)), + old_iv); + } + + position_type draw_com(cylindrical_pair_type const& domain, + time_type dt) + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // boost::shared_ptr const _structure( + // world_.get_structure( + // world_.find_molecule_info( + // domain.particles()[0].second.sid()).structure_id)); + // + // cylindrical_surface_type const* const structure( + // dynamic_cast(_structure.get())); + + // BOOST_ASSERT(structure); + + // length_type const r_R(draw_r( + // rng_, + // greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + // dt, domain.a_R())); + // return add( + // domain.shell().second.position(), + // multiply(structure->shape().unit_z(), r_R)); + } + + position_type draw_iv(cylindrical_pair_type const& domain, + time_type dt, position_type const& old_iv) + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // return multiply(domain.sigma(), normalize(old_iv)); + } + + draw_on_iv_reaction(rng_type& rng, world_type const& world) + : rng_(rng), world_(world) {} + + rng_type& rng_; + world_type const& world_; + }; + + struct draw_on_burst + { + position_type draw_com(spherical_pair_type const& domain, + time_type dt) + { + return add( + domain.shell().second.position(), + normalize( + create_vector( + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.), + rng_.uniform(-1., 1.)), + draw_r( + rng_, + greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + dt, domain.a_R()))); + } + + position_type draw_iv(spherical_pair_type const& domain, + time_type dt, position_type const& old_iv) + { + std::unique_ptr const gf( + choose_pair_greens_function(domain, dt)); + length_type const r(draw_r( + rng_, *gf, dt, domain.a_r(), domain.sigma())); + length_type const theta(draw_theta(rng_, *gf, dt, r)); + return adjust_iv_with_old_iv( + spherical_to_cartesian( + position_type(r, theta, rng_.uniform(0., 1.) * 2 * M_PI)), + old_iv); + } + + position_type draw_com(cylindrical_pair_type const& domain, + time_type dt) + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // boost::shared_ptr const _structure( + // world_.get_structure( + // world_.find_molecule_info( + // domain.particles()[0].second.sid()) + // .structure_id)); + + // cylindrical_surface_type const* const structure( + // dynamic_cast(_structure.get())); + + // BOOST_ASSERT(structure); + + // length_type const r_R(draw_r( + // rng_, + // greens_functions::GreensFunction3DAbsSym(domain.D_R(), domain.a_R()), + // dt, domain.a_R())); + // return add( + // domain.shell().second.position(), + // multiply(structure->shape().unit_z(), r_R)); + } + + position_type draw_iv(cylindrical_pair_type const& domain, + time_type dt, position_type const& old_iv) + { + throw ::ecell4::NotImplemented(""unsupported pair type.""); + // BOOST_ASSERT(::size(domain.reactions()) == 1); + // length_type const r( + // draw_r(rng_, + // greens_functions::GreensFunction3DRadAbs( + // domain.D_tot(), + // domain.reactions()[0].k(), domain.r0(), + // domain.sigma(), domain.a_r()), + // dt, domain.a_r(), domain.sigma())); + // return multiply(normalize(old_iv), r); + } + + draw_on_burst(rng_type& rng, world_type const& world) + : rng_(rng), world_(world) {} + + rng_type& rng_; + world_type const& world_; + }; +public: + typedef abstract_limited_generator domain_id_pair_generator; + +public: + virtual ~EGFRDSimulator() {} + + EGFRDSimulator( + const std::shared_ptr& world, + const std::shared_ptr& ecell4_model, + Real bd_dt_factor = 1e-5, int dissociation_retry_moves = 1, + length_type user_max_shell_size = std::numeric_limits::infinity()) + : base_type(world, ecell4_model), + bd_dt_factor_(bd_dt_factor), + num_retries_(dissociation_retry_moves), + user_max_shell_size_(user_max_shell_size), + ssmat_(new spherical_shell_matrix_type((*world).edge_lengths(), (*world).matrix_sizes())), + csmat_(new cylindrical_shell_matrix_type((*world).edge_lengths(), (*world).matrix_sizes())), + smatm_(boost::fusion::pair(ssmat_.get()), + boost::fusion::pair(csmat_.get())), + single_shell_factor_(.1), + multi_shell_factor_(.05), + rejected_moves_(0), zero_step_count_(0), dirty_(true) + { + std::fill(domain_count_per_type_.begin(), domain_count_per_type_.end(), 0); + std::fill(single_step_count_.begin(), single_step_count_.end(), 0); + std::fill(pair_step_count_.begin(), pair_step_count_.end(), 0); + std::fill(multi_step_count_.begin(), multi_step_count_.end(), 0); + } + + EGFRDSimulator( + const std::shared_ptr& world, + Real bd_dt_factor = 1e-5, int dissociation_retry_moves = 1, + length_type user_max_shell_size = std::numeric_limits::infinity()) + : base_type(world), + bd_dt_factor_(bd_dt_factor), + num_retries_(dissociation_retry_moves), + user_max_shell_size_(user_max_shell_size), + ssmat_(new spherical_shell_matrix_type((*world).edge_lengths(), (*world).matrix_sizes())), + csmat_(new cylindrical_shell_matrix_type((*world).edge_lengths(), (*world).matrix_sizes())), + smatm_(boost::fusion::pair(ssmat_.get()), + boost::fusion::pair(csmat_.get())), + single_shell_factor_(.1), + multi_shell_factor_(.05), + rejected_moves_(0), zero_step_count_(0), dirty_(true) + { + std::fill(domain_count_per_type_.begin(), domain_count_per_type_.end(), 0); + std::fill(single_step_count_.begin(), single_step_count_.end(), 0); + std::fill(pair_step_count_.begin(), pair_step_count_.end(), 0); + std::fill(multi_step_count_.begin(), multi_step_count_.end(), 0); + } + + length_type user_max_shell_size() const + { + return user_max_shell_size_; + } + + length_type max_shell_size() const + { + const position_type& cell_sizes((*base_type::world_).cell_sizes()); + const length_type min_cell_size( + std::min(cell_sizes[0], std::min(cell_sizes[1], cell_sizes[2]))); + return std::min(min_cell_size / 2 / + traits_type::SAFETY, + user_max_shell_size_); + } + + template + std::pair::type> + new_shell(domain_id_type const& did, Tshape const& shape) + { + typedef typename traits_type::template shell_generator::type shell_type; + std::pair const retval(shidgen_(), shell_type(did, shape)); + boost::fusion::at_key(smatm_)->update(retval); + return retval; + } + + template + std::pair const& get_shell(shell_id_type const& id) const + { + typedef typename boost::remove_pointer< + typename boost::fusion::result_of::value_at_key< + shell_matrix_map_type, T>::type>::type shell_matrix_type; + + shell_matrix_type const& smat(*boost::fusion::at_key(smatm_)); + + typename shell_matrix_type::const_iterator i(smat.find(id)); + if (i == smat.end()) + { + throw ::ecell4::NotFound( + (boost::format(""shell id #%s not found"") % boost::lexical_cast(id)).str()); + } + + return *i; + } + + std::pair get_shell(shell_id_type const& id) + { + shell_variant_type result; + boost::fusion::for_each(smatm_, shell_finder(id, result)); + return std::make_pair(id, result); + } + + std::shared_ptr get_domain(domain_id_type const& id) const + { + typename domain_map::const_iterator i(domains_.find(id)); + + if (i == domains_.end()) + { + throw ::ecell4::NotFound( + (boost::format(""domain id #%s not found"") % boost::lexical_cast(id)).str()); + } + + return (*i).second; + } + + domain_id_pair_generator* get_domains() const + { + return make_range_generator(domains_); + } + + typename domain_map::size_type num_domains() const + { + return domains_.size(); + } + + int num_domains_per_type(domain_kind kind) const + { + return domain_count_per_type_[kind]; + } + + int num_single_steps_per_type(single_event_kind kind) const + { + return single_step_count_[kind]; + } + + int num_pair_steps_per_type(pair_event_kind kind) const + { + return pair_step_count_[kind]; + } + + int num_multi_steps_per_type(typename multi_type::event_kind kind) const + { + return multi_step_count_[kind]; + } + + std::vector* + get_neighbor_domains(particle_shape_type const& p) + { + typedef domain_collector collector_type; + no_filter f; + collector_type col((*base_type::world_), p, f); + boost::fusion::for_each(smatm_, shell_collector_applier(col, p.position())); + return col.neighbors.container().get(); + } + + std::vector* + get_neighbor_domains(particle_shape_type const& p, domain_id_type const& ignore) + { + typedef domain_collector collector_type; + one_id_filter f(ignore); + collector_type col((*base_type::world_), p, f); + boost::fusion::for_each(smatm_, shell_collector_applier(col, p.position())); + return col.neighbors.container().get(); + } + + virtual void initialize() + { + const position_type& edge_lengths((*base_type::world_).edge_lengths()); + const typename world_type::matrix_sizes_type& + matrix_sizes((*base_type::world_).matrix_sizes()); + + domains_.clear(); + (*ssmat_).clear(); + (*csmat_).clear(); + scheduler_.clear(); + + if (edge_lengths != (*ssmat_).edge_lengths() + || matrix_sizes != (*ssmat_).matrix_sizes()) + { + std::unique_ptr + newssmat(new spherical_shell_matrix_type(edge_lengths, matrix_sizes)); + std::unique_ptr + newcsmat(new cylindrical_shell_matrix_type(edge_lengths, matrix_sizes)); + ssmat_.swap(newssmat); + csmat_.swap(newcsmat); + boost::fusion::at_key(smatm_) = ssmat_.get(); + boost::fusion::at_key(smatm_) = csmat_.get(); + } + + for (particle_id_pair const& pp: + (*base_type::world_).get_particles_range()) + { + std::shared_ptr single(create_single(pp)); + add_event(*single, SINGLE_EVENT_ESCAPE); + } + + for (reaction_rule_type const& rr: + (*base_type::network_rules_).zeroth_order_reaction_rules()) + { + add_event(rr); + } + dirty_ = false; + } + + /** + * override + * HERE + */ + + virtual Real next_time() const + { + return scheduler_.next_time(); + } + + virtual Real dt() const + { + return scheduler_.next_time() - base_type::t(); + } + + /** + * override + * THERE + */ + + virtual void step() + { + if (dirty_) + { + initialize(); + } + + _step(); + } + + void finalize() + { + std::vector non_singles; + + // first burst all Singles. + for (event_id_pair_type const& event: scheduler_.events()) + { + { + single_event const* single_ev( + dynamic_cast(event.second.get())); + if (single_ev) + { + burst(single_ev->domain()); + continue; + } + } + { + birth_event const* birth_ev( + dynamic_cast(event.second.get())); + if (birth_ev) + { + continue; + } + } + { + domain_event_base const* domain_ev( + dynamic_cast(event.second.get())); + BOOST_ASSERT(domain_ev); + non_singles.push_back(domain_ev->domain().id()); + // continue; + } + } + + // then burst all Pairs and Multis. + burst_domains(non_singles); + + base_type::dt_ = 0.; + } + + // virtual bool step(time_type upto) + virtual bool step(const time_type& upto) + { + if (dirty_) + { + initialize(); + } + + if (upto <= this->t()) + { + return false; + } + + // if (upto >= scheduler_.top().second->time()) + if (upto >= scheduler_.next_time()) + { + _step(); + return true; + } + + LOG_INFO((""stop at %.16g"", upto)); + + this->set_t(upto); + this->finalize(); + return false; + } + + // {{{ clear_volume + // called by Multi + void clear_volume(particle_shape_type const& p) + { + std::unique_ptr > domains( + get_neighbor_domains(p)); + if (domains) + { + burst_domains(*domains); + } + } + + void clear_volume(particle_shape_type const& p, + domain_id_type const& ignore) + { + std::unique_ptr > domains( + get_neighbor_domains(p, ignore)); + + if (domains) + { + burst_domains(*domains); + } + } + // }}} + + bool check() const + { + LOG_INFO((""checking overall consistency"")); + + bool retval(true); + + CHECK(this->t() >= 0.0); + CHECK(base_type::dt_ >= 0.0); + + typedef std::map > + domain_shell_association; + + domain_shell_association did_map; + + boost::fusion::for_each(smatm_, + domain_shell_map_builder( + (*base_type::world_), did_map)); + + std::set scheduled_domains; + typename domain_type::size_type shells_correspond_to_domains(0); + std::size_t particles_correspond_to_domains(0); + + for (typename event_scheduler_type::value_type const& value: + scheduler_.events()) + { + domain_type const& domain(dynamic_cast(*value.second).domain()); + CHECK(check_domain(domain)); + + if (!scheduled_domains.insert(domain.id()).second) + { + LOG_WARNING((""domain id %s is doubly scheduled!"", boost::lexical_cast(domain.id()).c_str())); + } + + CHECK(domain.event() == value); + + typename domain_type::size_type const num_shells(domain.num_shells()); + + shells_correspond_to_domains += num_shells; + particles_correspond_to_domains += domain.multiplicity(); + + typename std::set const& shell_ids( + did_map[domain.id()]); + CHECK(static_cast( + ecell4::egfrd::size(shell_ids)) == num_shells); + } + + CHECK((*base_type::world_).num_particles() == static_cast(particles_correspond_to_domains)); + + { + std::vector diff; + const auto first_selected = make_select_first_range(did_map); + std::set_difference( + std::begin(first_selected), std::end(first_selected), + std::begin(scheduled_domains), std::end(scheduled_domains), + std::back_inserter(diff)); + + if (diff.size() != 0) + { + LOG_WARNING((""domains not scheduled: %s"", + stringize_and_join(diff, "", "").c_str())); + for (domain_id_type const& domain_id: diff) + { + LOG_WARNING(("" shells that belong to unscheduled domain %s: %s"", + boost::lexical_cast(domain_id).c_str(), + stringize_and_join(did_map[domain_id], "", "").c_str())); + } + retval = false; + } + } + + std::set all_shell_ids; + boost::fusion::for_each(smatm_, + shell_id_collector >(all_shell_ids)); + + if (shells_correspond_to_domains != static_cast(ecell4::egfrd::size(all_shell_ids))) + { + LOG_WARNING((""shells_correspond_to_domains=%zu, shell_population=%zu"", shells_correspond_to_domains, static_cast(ecell4::egfrd::size(all_shell_ids)))); + dump_events(); + retval = false; + } + return retval; + } + + virtual bool check_reaction() const + { + return last_reactions().size() > 0; + } + + std::vector > last_reactions() const + { + return (*dynamic_cast*>( + base_type::rrec_.get())).last_reactions(); + } + +protected: + template + void move_shell(std::pair const& shell) + { + typedef Tshell shell_type; + boost::fusion::at_key(smatm_)->update(shell); + } + + template + void update_shell_matrix(AnalyticalSingle const& domain) + { + move_shell(domain.shell()); + } + + template + void update_shell_matrix(AnalyticalPair const& domain) + { + move_shell(domain.shell()); + } + + void update_shell_matrix(shaped_domain_type const& domain) + { + { + spherical_single_type const* _domain(dynamic_cast(&domain)); + if (_domain) { + update_shell_matrix(*_domain); + return; + } + } + { + cylindrical_single_type const* _domain(dynamic_cast(&domain)); + if (_domain) { + update_shell_matrix(*_domain); + return; + } + } + { + spherical_pair_type const* _domain(dynamic_cast(&domain)); + if (_domain) { + update_shell_matrix(*_domain); + return; + } + } + { + cylindrical_pair_type const* _domain(dynamic_cast(&domain)); + if (_domain) { + update_shell_matrix(*_domain); + return; + } + } + throw ::ecell4::NotImplemented(""unsupported domain type""); + } + + // remove_domain_but_shell {{{ + template + void remove_domain_but_shell(AnalyticalSingle& domain) + { + --domain_count_per_type_[get_domain_kind(domain)]; + _remove_domain_but_shell(domain); + } + + template + void remove_domain_but_shell(AnalyticalPair& domain) + { + --domain_count_per_type_[get_domain_kind(domain)]; + _remove_domain_but_shell(domain); + } + + void remove_domain_but_shell(multi_type& domain) + { + --domain_count_per_type_[get_domain_kind(domain)]; + _remove_domain_but_shell(domain); + } + + void remove_domain_but_shell(domain_type& domain) + { + --domain_count_per_type_[get_domain_kind(domain)]; + _remove_domain_but_shell(domain); + } + + void _remove_domain_but_shell(domain_type& domain) + { + LOG_DEBUG((""remove_domain_but_shell: %s"", boost::lexical_cast(domain.id()).c_str())); + event_id_type const event_id(domain.event().first); + + // domains_.erase(domain.id()); // this hits a bug in gcc 4.4 (at least)'s unordered_map. + typename domain_map::iterator domain_to_be_removed(domains_.find(domain.id())); + if (base_type::paranoiac_) + { + BOOST_ASSERT(domain_to_be_removed != domains_.end()); + } + domains_.erase(domain_to_be_removed); + + try + { + remove_event(event_id); + } + catch (std::out_of_range const&) + { + LOG_DEBUG((""event %s already removed; ignoring."", boost::lexical_cast(event_id).c_str())); + } + } + + // }}} + + // remove_domain {{{ + template + void remove_domain(AnalyticalSingle& domain) + { + typedef T shell_type; + boost::fusion::at_key(smatm_)->erase(domain.shell().first); + remove_domain_but_shell(domain); + } + + template + void remove_domain(AnalyticalPair& domain) + { + typedef T shell_type; + boost::fusion::at_key(smatm_)->erase(domain.shell().first); + remove_domain_but_shell(domain); + } + + void remove_domain(multi_type& domain) + { + for (spherical_shell_id_pair const& shell: domain.get_shells()) + { + boost::fusion::at_key(smatm_)->erase(shell.first); + } + remove_domain_but_shell(domain); + } + + void remove_domain(domain_type& domain) + { + { + spherical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + remove_domain(*_domain); + return; + } + } + { + cylindrical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + remove_domain(*_domain); + return; + } + } + { + spherical_pair_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + remove_domain(*_domain); + return; + } + } + { + cylindrical_pair_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + remove_domain(*_domain); + return; + } + } + { + multi_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + remove_domain(*_domain); + return; + } + } + throw ::ecell4::NotImplemented(std::string(""unsupported domain type"")); + } + // }}} + + void add_event(single_type& domain, single_event_kind const& kind) + { + if (base_type::paranoiac_) + BOOST_ASSERT(domains_.find(domain.id()) != domains_.end()); + + std::shared_ptr new_event( + new single_event(this->t() + domain.dt(), domain, kind)); + domain.event() = std::make_pair(scheduler_.add(new_event), new_event); + LOG_DEBUG((""add_event: #%d - %s"", domain.event().first, boost::lexical_cast(domain).c_str())); + } + + void add_event(pair_type& domain, pair_event_kind const& kind) + { + if (base_type::paranoiac_) + BOOST_ASSERT(domains_.find(domain.id()) != domains_.end()); + + std::shared_ptr new_event( + new pair_event(this->t() + domain.dt(), domain, kind)); + domain.event() = std::make_pair(scheduler_.add(new_event), new_event); + LOG_DEBUG((""add_event: #%d - %s"", domain.event().first, boost::lexical_cast(domain).c_str())); + } + + void add_event(multi_type& domain) + { + if (base_type::paranoiac_) + BOOST_ASSERT(domains_.find(domain.id()) != domains_.end()); + + std::shared_ptr new_event( + new multi_event(this->t() + domain.dt(), domain)); + domain.event() = std::make_pair(scheduler_.add(new_event), new_event); + LOG_DEBUG((""add_event: #%d - %s"", domain.event().first, boost::lexical_cast(domain).c_str())); + } + + /** + * The following add_event function is for birth_event. + */ + void add_event(reaction_rule_type const& rr) + { + const double rnd(this->rng().uniform(0, 1)); + const double dt(gsl_sf_log(1.0 / rnd) / double(rr.k() * (*base_type::world_).volume())); + std::shared_ptr new_event(new birth_event(this->t() + dt, rr)); + scheduler_.add(new_event); + } + + void remove_event(event_id_type const& id) + { + LOG_DEBUG((""remove_event: #%d"", id)); + scheduler_.remove(id); + } + + void remove_event(domain_type const& domain) + { + remove_event(domain.event().first); + } + + // create_single {{{ + std::shared_ptr create_single(particle_id_pair const& p) + { + domain_kind kind(NONE); + single_type* new_single(0); + domain_id_type did(didgen_()); + + struct factory: ImmutativeStructureVisitor + { + virtual ~factory() {} + + // virtual void operator()(spherical_surface_type const& structure) const + // { + // throw ::ecell4::NotImplemented( + // (boost::format(""unsupported structure type: %s"") % + // boost::lexical_cast(structure)).str()); + // } + + // virtual void operator()(cylindrical_surface_type const& structure) const + // { + // // Heads up. The cylinder's *size*, not radius, is changed when + // // you make the cylinder bigger, because of the redefinition of + // // set_radius. + // // The radius of a rod is not more than it has to be (namely + // // the radius of the particle), so if the particle undergoes an + // // unbinding reaction, we still have to clear the target volume + // // and the move may be rejected (NoSpace error). + // const cylindrical_shell_id_pair new_shell( + // _this->new_shell( + // did, typename cylindrical_shell_type::shape_type( + // p.second.position(), p.second.radius(), + // structure.shape().unit_z(), + // p.second.radius()))); + // new_single = new cylindrical_single_type(did, p, new_shell); + // kind = CYLINDRICAL_SINGLE; + // } + + // virtual void operator()(planar_surface_type const& structure) const + // { + // cylindrical_shell_id_pair const new_shell( + // _this->new_shell(did, typename cylindrical_shell_type::shape_type( + // p.second.position(), p.second.radius(), + // normalize(cross_product( + // structure.shape().unit_x(), + // structure.shape().unit_y())), + // p.second.radius()))); + // new_single = new cylindrical_single_type(did, p, new_shell); + // kind = CYLINDRICAL_SINGLE; + // } + + virtual void operator()(cuboidal_region_type const& structure) const + { + spherical_shell_id_pair new_shell( + _this->new_shell( + did, typename spherical_shell_type::shape_type( + p.second.position(), p.second.radius()))); + // _this->new_shell(did, ::shape(p.second))); + new_single = new spherical_single_type(did, p, new_shell); + kind = SPHERICAL_SINGLE; + } + + factory(EGFRDSimulator* _this, particle_id_pair const& p, + domain_id_type const& did, single_type*& new_single, + domain_kind& kind) + : _this(_this), p(p), did(did), new_single(new_single), + kind(kind) {} + + EGFRDSimulator* _this; + particle_id_pair const& p; + domain_id_type const& did; + single_type*& new_single; + domain_kind& kind; + }; + + molecule_info_type const species((*base_type::world_).get_molecule_info(p.second.species())); + // molecule_info_type const& species((*base_type::world_).find_molecule_info(p.second.species())); + dynamic_cast(*(*base_type::world_).get_structure(species.structure_id)).accept(factory(this, p, did, new_single, kind)); + std::shared_ptr const retval(new_single); + domains_.insert(std::make_pair(did, retval)); + BOOST_ASSERT(kind != NONE); + ++domain_count_per_type_[kind]; + return std::dynamic_pointer_cast(retval); + } + // }}} + + // create_pair {{{ + std::shared_ptr create_pair(particle_id_pair const& p0, + particle_id_pair const& p1, + position_type const& com, + position_type const& iv, + length_type shell_size) + { + domain_kind kind(NONE); + pair_type* new_pair(0); + domain_id_type did(didgen_()); + + struct factory: ImmutativeStructureVisitor + { + // virtual void operator()(spherical_surface_type const& structure) const + // { + // throw ::ecell4::NotImplemented( + // (boost::format(""unsupported structure type: %s"") % + // boost::lexical_cast(structure)).str()); + // } + + // virtual void operator()(cylindrical_surface_type const& structure) const + // { + // // The radius of a rod is not more than it has to be (namely + // // the radius of the biggest particle), so if the particle + // // undergoes an unbinding reaction we still have to clear the + // // target volume and the move may be rejected (NoSpace error). + // cylindrical_shell_id_pair const new_shell( + // _this->new_shell(did, typename cylindrical_shell_type::shape_type( + // com, + // shell_size, + // shape(structure).unit_z(), + // std::max(p0.second.radius(), p1.second.radius())))); + // new_pair = new cylindrical_pair_type(did, p0, p1, new_shell, + // iv, rules); + // kind = CYLINDRICAL_PAIR; + // } + + + // virtual void operator()(planar_surface_type const& structure) const + // { + // cylindrical_shell_id_pair const new_shell( + // _this->new_shell(did, typename cylindrical_shell_type::shape_type( + // com, + // shell_size, + // normalize(cross_product( + // shape(structure).unit_x(), + // shape(structure).unit_y())), + // std::max(p0.second.radius(), p1.second.radius())))); + // new_pair = new cylindrical_pair_type(did, p0, p1, new_shell, + // iv, rules); + // kind = CYLINDRICAL_PAIR; + // } + + virtual void operator()(cuboidal_region_type const& structure) const + { + spherical_shell_id_pair new_shell( + _this->new_shell(did, + typename spherical_shell_type::shape_type(com, shell_size))); + new_pair = new spherical_pair_type(did, p0, p1, new_shell, + iv, rules); + kind = SPHERICAL_PAIR; + } + + factory(EGFRDSimulator* _this, particle_id_pair const& p0, + particle_id_pair const& p1, position_type const& com, + position_type const& iv, length_type shell_size, + domain_id_type const& did, pair_type*& new_pair, + domain_kind& kind) + : _this(_this), p0(p0), p1(p1), com(com), iv(iv), + shell_size(shell_size), did(did), + rules((*_this->network_rules_).query_reaction_rule( + p0.second.species(), p1.second.species())), + new_pair(new_pair), kind(kind) {} + + EGFRDSimulator* _this; + particle_id_pair const& p0; + particle_id_pair const& p1; + position_type const& com; + position_type const& iv; + const length_type shell_size; + domain_id_type const& did; + typename network_rules_type::reaction_rule_vector const& rules; + pair_type*& new_pair; + domain_kind& kind; + }; + + molecule_info_type const species((*base_type::world_).get_molecule_info(p0.second.species())); + // molecule_info_type const& species((*base_type::world_).find_molecule_info(p0.second.species())); + dynamic_cast(*(*base_type::world_).get_structure(species.structure_id)).accept(factory(this, p0, p1, com, iv, shell_size, did, new_pair, kind)); + + std::shared_ptr const retval(new_pair); + domains_.insert(std::make_pair(did, retval)); + BOOST_ASSERT(kind != NONE); + ++domain_count_per_type_[kind]; + return std::dynamic_pointer_cast(retval); + } + // }}} + + // create_multi {{{ + std::shared_ptr create_multi() + { + domain_id_type did(didgen_()); + multi_type* new_multi(new multi_type(did, *this, bd_dt_factor_)); + std::shared_ptr const retval(new_multi); + domains_.insert(std::make_pair(did, retval)); + ++domain_count_per_type_[MULTI]; + return std::dynamic_pointer_cast(retval); + } + // }}} + + // draw_r {{{ + template + static length_type draw_r(rng_type& rng, + Tgf const& gf, + time_type dt, + length_type a, + length_type sigma = -1.) + { + LOG_DEBUG((""draw_r: dt=%.16g, a=%.16g, sigma=%.16g"", dt, a, sigma)); + BOOST_ASSERT(a > sigma && a >= 0.); + length_type r(0.); + double rnd(0.); + try + { + do + { + rnd = rng.uniform(0., 1.); + r = gf.drawR(rnd, dt); + } while (r > a || r <= sigma); + } + catch (std::exception const& e) + { + throw PropagationError( + (boost::format( + ""gf.drawR() failed: %s, gf=%s, rnd=%.16g, dt=%.16g, a=%.16g, sigma=%.16g: %s"") % e.what() % gf.getName() % rnd % dt % a % sigma % gf.dump()).str()); + } + + return r; + } + // }}} + + // draw_theta {{{ + template + static length_type draw_theta(rng_type& rng, + Tgf const& gf, + time_type dt, + length_type r) + { + length_type theta(0.); + double rnd(0.); + try + { + rnd = rng.uniform(0., 1.); + theta = gf.drawTheta(rnd, r, dt); + } + catch (std::exception const& e) + { + throw PropagationError( + (boost::format( + ""gf.drawTheta() failed: %s, gf=%s, rnd=%.16g, dt=%.16g, r=%.16g: %s"") % e.what() % gf.getName() % rnd % dt % r % gf.dump()).str()); + } + + return theta; + } + // }}} + + // draw_displacement {{{ + position_type draw_displacement( + AnalyticalSingle const& domain, + length_type r) + { + // const double cos_theta(this->rng().uniform(-1., 1.)); + // const double sin_theta(sqrt(1 - cos_theta * cos_theta)); + // double sin_phi, cos_phi; + // sincos(this->rng().uniform(0., 2 * M_PI), &sin_phi, &cos_phi); + // return normalize( + // create_vector( + // sin_theta * cos_phi, sin_theta * sin_phi, cos_theta), r); + + // double x, y, z; + // this->rng().dir_3d(&x, &y, &z); + // return normalize( + // create_vector(x, y, z), r); + + // return this->rng().direction3d(r); + return normalize(this->rng().direction3d(1), r); + } + + position_type draw_displacement( + AnalyticalSingle const& domain, + length_type r) + { + // return multiply(shape(domain.shell().second).unit_z(), r); + return multiply(shape(domain.shell().second).axis(), r); + } + // }}} + + // draw_new_position {{{ + template + position_type draw_new_position( + AnalyticalSingle const& domain, + time_type dt) + { + typedef Tshell shell_type; + typedef typename shell_type::shape_type shape_type; + typedef typename detail::get_greens_function::type greens_function; + length_type const r( + draw_r( + this->rng(), + greens_function( + domain.particle().second.D(), + domain.mobility_radius()), + dt, + domain.mobility_radius())); + position_type const displacement(draw_displacement(domain, r)); + LOG_DEBUG((""draw_new_position(domain=%s, dt=%.16g): mobility_radius=%.16g, r=%.16g, displacement=%s (%.16g)"", + boost::lexical_cast(domain).c_str(), dt, + domain.mobility_radius(), + r, boost::lexical_cast(displacement).c_str(), + length(displacement))); + if (base_type::paranoiac_) + { + BOOST_ASSERT(r <= domain.mobility_radius()); + // length_type const scale(domain.particle().second.radius()); + // BOOST_ASSERT(feq(length(displacement), std::abs(r), scale)); + } + return (*base_type::world_).apply_boundary(add(domain.particle().second.position(), displacement)); + } + + position_type draw_new_position(single_type& domain, time_type dt) + { + { + spherical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + return draw_new_position(*_domain, dt); + } + } + { + cylindrical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + return draw_new_position(*_domain, dt); + } + } + throw ::ecell4::NotImplemented(std::string(""unsupported domain type"")); + } + // }}} + + template + position_type draw_escape_position( + AnalyticalSingle const& domain) + { + position_type const displacement(draw_displacement(domain, domain.mobility_radius())); + LOG_DEBUG((""draw_escape_position(domain=%s): mobility_radius=%.16g, displacement=%s (%.16g)"", + boost::lexical_cast(domain).c_str(), + domain.mobility_radius(), + boost::lexical_cast(displacement).c_str(), + length(displacement))); + if (base_type::paranoiac_) + { + ; // do nothing + // BOOST_ASSERT(feq(length(displacement)) <= domain.mobility_radius()); + // length_type const scale(domain.particle().second.radius()); + // BOOST_ASSERT(feq(length(displacement), std::abs(domain.mobility_radius()), scale)); + } + return (*base_type::world_).apply_boundary(add(domain.particle().second.position(), displacement)); + } + + position_type draw_escape_position(single_type& domain) + { + { + spherical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + return draw_escape_position(*_domain); + } + } + { + cylindrical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + return draw_escape_position(*_domain); + } + } + throw ::ecell4::NotImplemented(std::string(""unsupported domain type"")); + } + + // draw_new_positions {{{ + template + std::array draw_new_positions( + AnalyticalPair const& domain, time_type dt) + { + Tdraw d(this->rng(), *base_type::world_); + position_type const new_com(d.draw_com(domain, dt)); + position_type const new_iv(d.draw_iv(domain, dt, domain.iv())); + D_type const D0(domain.particles()[0].second.D()); + D_type const D1(domain.particles()[1].second.D()); + return array_gen( + (*base_type::world_).apply_boundary(subtract(new_com, multiply(new_iv, D0 / (D0 + D1)))), + (*base_type::world_).apply_boundary(add(new_com, multiply(new_iv, D1 / (D0 + D1))))); + } + // }}} + + // propagate {{{ + /** + * The difference between a burst and a propagate is that a burst + * always takes place before the actual scheduled event for the single, + * while propagate_single can be called for an escape event. + * + * Another subtle difference is that burst_single always reschedules + * (update_event) the single, while just calling propagate does not. + * So whoever calls propagate_single directly should reschedule the single + * afterwards. + */ + //template + //void propagate(AnalyticalSingle& domain, position_type const& new_pos) + void propagate(single_type& domain, position_type const& new_pos, + bool do_update_shell_matrix) + { + LOG_DEBUG((""propagate: domain=%s, new_pos=%s, do_update_shell_matrix=%d"", + boost::lexical_cast(domain).c_str(), + boost::lexical_cast(new_pos).c_str(), + do_update_shell_matrix)); + + if (base_type::paranoiac_) + { + particle_shape_type const new_particle(new_pos, domain.particle().second.radius()); + BOOST_ASSERT(check_overlap(new_particle, domain.particle().first)); + } + + particle_type const& old(domain.particle().second); + domain.particle().second = particle_type(old.sid(), + new_pos, old.radius(), old.D()); + (*base_type::world_).update_particle( + domain.particle().first, domain.particle().second); + + domain.position() = new_pos; + domain.size() = domain.particle().second.radius(); + if (do_update_shell_matrix) + update_shell_matrix(domain); + } + + template + std::array, 2> + propagate(AnalyticalPair& domain, + std::array const& new_pos) + { + std::array const& particles(domain.particles()); + std::array new_particles(particles); + new_particles[0].second.position() = new_pos[0]; + new_particles[1].second.position() = new_pos[1]; + + if (base_type::paranoiac_) + { + BOOST_ASSERT(distance(domain, new_particles[0].second.position()) <= -new_particles[0].second.radius()); + BOOST_ASSERT(distance(domain, new_particles[1].second.position()) <= -new_particles[1].second.radius()); + BOOST_ASSERT(check_overlap( + shape(new_particles[0].second), + new_particles[0].first, new_particles[1].first)); + BOOST_ASSERT(check_overlap( + shape(new_particles[1].second), + new_particles[0].first, new_particles[1].first)); + BOOST_ASSERT(check_pair_pos(domain, new_particles)); + } + + (*base_type::world_).update_particle( + new_particles[0].first, new_particles[0].second); + (*base_type::world_).update_particle( + new_particles[1].first, new_particles[1].second); + + remove_domain(domain); + + std::array, 2> const singles = { { + create_single(new_particles[0]), + create_single(new_particles[1]) + } }; + + if (log_.level() == Logger::L_DEBUG) + { + for (int i = 0; i < 2; i++) + { + LOG_DEBUG((""propagate: #%d: %s => %s"", i, + boost::lexical_cast(particles[i].second.position()).c_str(), + boost::lexical_cast(*singles[i]).c_str())); + } + } + + return singles; + } + // }}} + + + template + void burst_domains(Trange const& domain_ids, boost::optional >&> const& result = boost::optional >&>()) + { + for(domain_id_type id: domain_ids) + { + std::shared_ptr domain(get_domain(id)); + burst(domain, result); + } + } + + // burst {{{ + template + void burst(AnalyticalSingle& domain) + { + position_type const old_pos(domain.position()); + //length_type const old_shell_size(domain.size()); + length_type const particle_radius(domain.particle().second.radius()); + + // Override dt, burst happens before single's scheduled event. + domain.dt() = this->t() - domain.last_time(); + LOG_DEBUG((""t=%.16g, domain.last_time=%.16g"", this->t(), domain.last_time())); + + position_type const new_pos(draw_new_position(domain, domain.dt())); + + propagate(domain, new_pos, true); + + domain.last_time() = this->t(); + domain.dt() = 0.; + try + { + remove_event(domain); + add_event(domain, SINGLE_EVENT_ESCAPE); + } + catch (std::out_of_range const&) + { + // event may have been removed. + LOG_DEBUG((""event %s already removed; ignoring."", boost::lexical_cast(domain.event().first).c_str())); + } + + // Displacement check is in draw_new_position. + // BOOST_ASSERT( + // (*base_type::world_).distance(new_pos, old_pos) + // <= old_shell_size - particle_radius); + + BOOST_ASSERT(domain.size() == particle_radius); + } + + template + std::array, 2> burst(AnalyticalPair& domain) + { + length_type const dt(this->t() - domain.last_time()); + + std::array, 2> const singles( + propagate(domain, draw_new_positions(domain, dt))); + + add_event(*singles[0], SINGLE_EVENT_ESCAPE); + add_event(*singles[1], SINGLE_EVENT_ESCAPE); + + return singles; + } + + void burst(multi_type& domain, boost::optional >&> const& result = boost::optional >&>()) + { + for(particle_id_pair p: domain.get_particles_range()) + { + std::shared_ptr s(create_single(p)); + add_event(*s, SINGLE_EVENT_ESCAPE); + if (result) + { + result.get().push_back(std::dynamic_pointer_cast(s)); + } + } + remove_domain(domain); + } + + void burst(single_type& domain) + { + LOG_DEBUG((""burst: bursting %s"", boost::lexical_cast(domain).c_str())); + BOOST_ASSERT(this->t() >= domain.last_time()); + BOOST_ASSERT(this->t() <= domain.last_time() + domain.dt()); + { + spherical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + burst(*_domain); + return; + } + } + { + cylindrical_single_type* _domain(dynamic_cast(&domain)); + if (_domain) + { + burst(*_domain); + return; + } + } + throw ::ecell4::NotImplemented(""?""); + } + + void burst(std::shared_ptr domain, boost::optional >&> const& result = boost::optional >&>()) + { + LOG_DEBUG((""burst: bursting %s"", boost::lexical_cast(*domain).c_str())); + { + spherical_single_type* _domain(dynamic_cast(domain.get())); + if (_domain) + { + burst(*_domain); + if (result) + result.get().push_back(domain); + return; + } + } + { + cylindrical_single_type* _domain(dynamic_cast(domain.get())); + if (_domain) + { + burst(*_domain); + if (result) + result.get().push_back(domain); + return; + } + } + { + spherical_pair_type* _domain(dynamic_cast(domain.get())); + if (_domain) + { + std::array, 2> bursted(burst(*_domain)); + if (result) + { + result.get().push_back(std::dynamic_pointer_cast(bursted[0])); + result.get().push_back(std::dynamic_pointer_cast(bursted[1])); + } + return; + } + } + { + cylindrical_pair_type* _domain(dynamic_cast(domain.get())); + if (_domain) + { + std::array, 2> bursted(burst(*_domain)); + if (result) + { + result.get().push_back(std::dynamic_pointer_cast(bursted[0])); + result.get().push_back(std::dynamic_pointer_cast(bursted[1])); + } + return; + } + } + { + multi_type* _domain(dynamic_cast(domain.get())); + if (_domain) + { + burst(*_domain, result); + return; + } + } + throw ::ecell4::NotImplemented(""?""); + } + // }}} + + // attempt_single_reaction {{{ + bool attempt_single_reaction(single_type& domain) + { + const particle_id_pair reactant(domain.particle()); + const molecule_info_type reactant_species((*base_type::world_).get_molecule_info(reactant.second.species())); + // const molecule_info_type reactant_species((*base_type::world_).find_molecule_info(reactant.second.species())); + reaction_rules const& rules((*base_type::network_rules_).query_reaction_rule(reactant.second.species())); + if (ecell4::egfrd::size(rules) == 0) + { + return false; + } + + reaction_rule_type const& r(draw_reaction_rule(rules)); + LOG_DEBUG((""attempt_single_reaction: reactant=%s, products=[%s]"", + boost::lexical_cast(reactant.second.sid()).c_str(), + stringize_and_join(r.get_products(), "", "").c_str())); + + switch (ecell4::egfrd::size(r.get_products())) + { + case 0: + remove_domain(domain); + (*base_type::world_).remove_particle(reactant.first); + if (base_type::rrec_) + { + // (*base_type::rrec_)(reaction_record_type( + // r.id(), array_gen(), reactant.first)); + (*base_type::rrec_)(reaction_record_type( + r.id(), array_gen(), reactant)); + } + break; + case 1: + { + species_id_type const& product_id0(r.get_products()[0]); + molecule_info_type const product_species( + (*base_type::world_).get_molecule_info(product_id0)); + + if (reactant_species.radius < product_species.radius) + clear_volume(ecell4::egfrd::shape(reactant.second), domain.id()); + + if (!(*base_type::world_).no_overlap( + ecell4::egfrd::shape(reactant.second), reactant.first)) + { + LOG_INFO((""no space for product particle."")); + throw NoSpace(); + } + + remove_domain(domain); + (*base_type::world_).remove_particle(reactant.first); + // particle_id_pair product( + // (*base_type::world_).new_particle( + // product_species.id(), reactant.second.position()).first); + particle_id_pair product( + (*base_type::world_).new_particle( + product_id0, reactant.second.position()).first); + std::shared_ptr new_domain(create_single(product)); + add_event(*new_domain, SINGLE_EVENT_ESCAPE); + if (base_type::rrec_) + { + // (*base_type::rrec_)(reaction_record_type( + // r.id(), array_gen(product.first), reactant.first)); + (*base_type::rrec_)(reaction_record_type( + r.id(), array_gen(product), reactant)); + } + } + break; + case 2: + { + species_id_type const& product_id0(r.get_products()[0]); + species_id_type const& product_id1(r.get_products()[1]); + // molecule_info_type const* const product_species[] = { + // &(*base_type::world_).get_molecule_info(product_id0), + // &(*base_type::world_).get_molecule_info(product_id1) + // }; + + // D_type const D0(product_species[0]->D), D1(product_species[1]->D); + // length_type const radius0(product_species[0]->radius), + // radius1(product_species[1]->radius); + molecule_info_type const product_species[] = { + (*base_type::world_).get_molecule_info(product_id0), + (*base_type::world_).get_molecule_info(product_id1) + }; + + D_type const D0(product_species[0].D), D1(product_species[1].D); + length_type const radius0(product_species[0].radius), + radius1(product_species[1].radius); + D_type const D01(D0 + D1); + length_type r01(radius0 + radius1); + Real const rad(std::max( + r01 * (D0 / D01) + radius0, r01 * (D1 / D01) + radius1)); + clear_volume(particle_shape_type(reactant.second.position(), rad), domain.id()); + + particle_shape_type new_particles[2]; + + int i = num_retries_; + while (--i >= 0) + { + std::shared_ptr structure( + (*base_type::world_).get_structure( + reactant_species.structure_id)); + position_type vector( + structure->random_vector( + r01 * traits_type::MINIMAL_SEPARATION_FACTOR, + this->rng())); + // place particles according to the ratio D1:D2 + // this way, species with D=0 doesn't move. + // FIXME: what if D1 == D2 == 0? + for (;;) { + new_particles[0] = particle_shape_type( + (*base_type::world_).apply_boundary( + add(reactant.second.position(), + multiply(vector, D0 / D01))), + radius0); + new_particles[1] = particle_shape_type( + (*base_type::world_).apply_boundary( + add(reactant.second.position(), + multiply(vector, -D1 / D01))), + radius1); + + length_type const distance_between_new_particles( + (*base_type::world_).distance( + new_particles[0].position(), + new_particles[1].position())); + if (distance_between_new_particles >= r01) + break; + + vector = multiply(vector, 1.0 + 1e-7); + } + + // accept the new positions if there is enough space. + if (((*base_type::world_).no_overlap( + new_particles[0], reactant.first)) && + ((*base_type::world_).no_overlap( + new_particles[1], reactant.first))) + break; + } + if (i < 0) + { + LOG_INFO((""no space for product particles."")); + throw NoSpace(); + } + + remove_domain(domain); + (*base_type::world_).remove_particle(reactant.first); + + particle_id_pair const pp[] = { + (*base_type::world_).new_particle( + product_id0, new_particles[0].position()).first, + (*base_type::world_).new_particle( + product_id1, new_particles[1].position()).first + }; + // create domains for two particles and add them to + // the event queue + add_event(*create_single(pp[0]), SINGLE_EVENT_ESCAPE); + add_event(*create_single(pp[1]), SINGLE_EVENT_ESCAPE); + + if (base_type::rrec_) + { + // (*base_type::rrec_)(reaction_record_type( + // r.id(), array_gen(pp[0].first, pp[1].first), + // reactant.first)); + (*base_type::rrec_)(reaction_record_type( + r.id(), array_gen(pp[0], pp[1]), reactant)); + } + } + break; + default: + throw ::ecell4::NotImplemented(""reactions that produces more than two products are not supported.""); + } + return true; + } + // }}} + + time_type draw_single_reaction_time(species_id_type const& sid) + { + reaction_rules const& rules( + (*base_type::network_rules_).query_reaction_rule(sid)); + rate_type const k_tot(calculate_k_tot(rules)); + if (k_tot <= 0.) + { + return std::numeric_limits::infinity(); + } + else if (k_tot == std::numeric_limits::infinity()) + { + return 0.; + } + else + { + const double rnd(this->rng().uniform(0., 1.)); + if(rnd <= 0.) + { + return std::numeric_limits::infinity(); + } + else + { + return (1. / k_tot) * (- std::log(rnd)); // log(1/x) == - log(x) + } + } + } + + template + time_type draw_escape_or_interaction_time(AnalyticalSingle const& domain) + { + if (domain.particle().second.D() == 0.) + { + return std::numeric_limits::infinity(); + } + else + { + typedef Tshell shell_type; + typedef typename shell_type::shape_type shape_type; + typedef typename detail::get_greens_function::type greens_function; + return greens_function(domain.particle().second.D(), + domain.mobility_radius()) + .drawTime(this->rng().uniform(0., 1.)); + } + } + + template + std::pair + draw_com_escape_or_iv_event_time(AnalyticalPair const& domain) + { + typedef Tshell shell_type; + typedef typename shell_type::shape_type shape_type; + typedef typename detail::get_pair_greens_function pair_greens_functions; + typedef typename pair_greens_functions::iv_type iv_greens_function; + typedef typename pair_greens_functions::com_type com_greens_function; +// BOOST_ASSERT(::size(domain.reactions()) == 1); + time_type const dt_com( + com_greens_function(domain.D_R(), domain.a_R()).drawTime(this->rng().uniform(0., 1.))); + + Real k_tot = 0; + for(reaction_rule_type const& rule: domain.reactions()) + { + k_tot += rule.k(); + } + time_type const dt_iv( + iv_greens_function(domain.D_tot(), k_tot, + domain.r0(), domain.sigma(), domain.a_r()).drawTime(this->rng().uniform(0., 1.))); + if (dt_com < dt_iv) + { + return std::make_pair(dt_com, PAIR_EVENT_COM_ESCAPE); + } + else + { + return std::make_pair(dt_iv, PAIR_EVENT_IV_UNDETERMINED); + } + } + + template + std::pair + draw_single_reaction_time(AnalyticalPair const& domain) + { + time_type const dt[2] = { + draw_single_reaction_time(domain.particles()[0].second.species()), + draw_single_reaction_time(domain.particles()[1].second.species()) + }; + if (dt[0] < dt[1]) + { + return std::make_pair(dt[0], PAIR_EVENT_SINGLE_REACTION_0); + } + else + { + return std::make_pair(dt[1], PAIR_EVENT_SINGLE_REACTION_1); + } + } + + // {{{ determine_next_event + template + void determine_next_event(AnalyticalSingle& domain) + { + // typedef Tshell shell_type; + // typedef typename shell_type::shape_type shape_type; + // typedef typename detail::get_greens_function::type greens_function; + time_type const dt_reaction(draw_single_reaction_time(domain.particle().second.species())); + time_type const dt_escape_or_interaction(draw_escape_or_interaction_time(domain)); + LOG_DEBUG((""determine_next_event: %s => dt_reaction=%.16g, "" + ""dt_escape_or_interaction=%.16g"", + boost::lexical_cast(domain).c_str(), + dt_reaction, dt_escape_or_interaction)); + single_event_kind event_kind; + if (dt_reaction < dt_escape_or_interaction) + { + domain.dt() = dt_reaction; + event_kind = SINGLE_EVENT_REACTION; + } + else + { + domain.dt() = dt_escape_or_interaction; + event_kind = SINGLE_EVENT_ESCAPE; + } + + domain.last_time() = this->t(); + add_event(domain, event_kind); + } + + void determine_next_event(single_type& domain) + { + { + spherical_single_type* _domain( + dynamic_cast(&domain)); + if (_domain) + { + determine_next_event(*_domain); + return; + } + } + { + cylindrical_single_type* _domain( + dynamic_cast(&domain)); + if (_domain) + { + determine_next_event(*_domain); + return; + } + } + throw ::ecell4::NotImplemented(""unsupported domain type""); + } + + template + void determine_next_event(AnalyticalPair& domain) + { + std::pair const dt_reaction(draw_single_reaction_time(domain)); + std::pair const dt_com_escape_or_iv_event(draw_com_escape_or_iv_event_time(domain)); + std::pair const dt_and_event_pair( + dt_reaction.first < dt_com_escape_or_iv_event.first ? + dt_reaction: dt_com_escape_or_iv_event); + domain.dt() = dt_and_event_pair.first; + domain.last_time() = this->t(); + add_event(domain, dt_and_event_pair.second); + } + + void determine_next_event(pair_type& domain) + { + { + spherical_pair_type* _domain( + dynamic_cast(&domain)); + if (_domain) + { + determine_next_event(*_domain); + return; + } + } + { + cylindrical_pair_type* _domain( + dynamic_cast(&domain)); + if (_domain) + { + determine_next_event(*_domain); + return; + } + } + throw ::ecell4::NotImplemented(""unsupported domain type""); + } + // }}} + + // get_intruders {{{ + std::pair*, + std::pair > + get_intruders(particle_shape_type const& p, + domain_id_type const& ignore) const + { + typedef intruder_collector collector_type; + + collector_type col((*base_type::world_), p, ignore); + boost::fusion::for_each(smatm_, shell_collector_applier(col, p.position())); + return std::make_pair(col.intruders.container().get(), col.closest); + } + // }}} + + template + std::pair + get_closest_domain(position_type const& p, TdidSet const& ignore) const + { + typedef closest_object_finder collector_type; + + collector_type col((*base_type::world_), p, ignore); + boost::fusion::for_each(smatm_, shell_collector_applier(col, p)); + return col.closest; + } + + void restore_domain(single_type& domain) + { + std::pair const closest( + get_closest_domain( + domain.position(), + array_gen(domain.id()))); + restore_domain(domain, closest); + } + + template + void restore_domain(AnalyticalSingle& domain, + std::pair const& closest) + { + // typedef typename AnalyticalSingle::shell_type shell_type; + domain_type const* closest_domain( + closest.second == std::numeric_limits::infinity() ? + (domain_type const*)0: get_domain(closest.first).get()); + length_type new_shell_size(0.); + + if (closest_domain) + { + single_type const* const _closest_domain( + dynamic_cast(closest_domain)); + if (_closest_domain) + { + length_type const distance_to_closest( + (*base_type::world_).distance( + domain.position(), _closest_domain->position())); + new_shell_size = calculate_single_shell_size( + domain, *_closest_domain, + distance_to_closest, + closest.second); + } else { + new_shell_size = closest.second / traits_type::SAFETY; + } + new_shell_size = std::min(max_shell_size(), + std::max(domain.particle().second.radius(), new_shell_size)); + } + else + { + new_shell_size = max_shell_size(); + } + LOG_DEBUG((""restore domain: %s (shell_size=%.16g, dt=%.16g) closest=%s (distance=%.16g)"", + boost::lexical_cast(domain).c_str(), + new_shell_size, + domain.dt(), + closest_domain ? + boost::lexical_cast(*closest_domain).c_str(): + ""(none)"", + closest.second)); + if (base_type::paranoiac_) + { + BOOST_ASSERT(check_overlap( + particle_shape_type(domain.position(), new_shell_size), + domain.particle().first)); + } + domain.size() = new_shell_size; + update_shell_matrix(domain); + BOOST_ASSERT(domain.size() == new_shell_size); + } + + void restore_domain(single_type& domain, + std::pair const& closest) + { + { + spherical_single_type *_domain( + dynamic_cast(&domain)); + if (_domain) + return restore_domain(*_domain, closest); + } + { + cylindrical_single_type *_domain( + dynamic_cast(&domain)); + if (_domain) + return restore_domain(*_domain, closest); + } + throw ::ecell4::NotImplemented(std::string(""unsupported domain type"")); + } + + template + void burst_non_multis(Trange const& domain_ids, + std::vector >& bursted) + { + for (domain_id_type id: domain_ids) + { + std::shared_ptr domain(get_domain(id)); + if (dynamic_cast(domain.get())) + { + bursted.push_back(domain); + } + else + { + burst(domain, bursted); + } + } + } + + template + length_type distance(AnalyticalSingle const& domain, + position_type const& pos) const + { + return (*base_type::world_).distance(shape(domain.shell().second), pos); + } + + template + length_type distance(AnalyticalPair const& domain, + position_type const& pos) const + { + return (*base_type::world_).distance(shape(domain.shell().second), pos); + } + + length_type distance(multi_type const& domain, position_type const& pos) const + { + length_type retval(std::numeric_limits::infinity()); + for (spherical_shell_id_pair const& shell: domain.get_shells()) + { + length_type const dist((*base_type::world_).distance( + shape(shell.second), pos)); + if (retval > dist) + { + retval = dist; + } + } + return retval; + } + + length_type distance(domain_type const& domain, position_type const& pos) const + { + length_type retval; + + struct distance_visitor: ImmutativeDomainVisitor + { + virtual ~distance_visitor() {} + + virtual void operator()(multi_type const& domain) const + { + retval = outer.distance(domain, pos); + } + + virtual void operator()(spherical_single_type const& domain) const + { + retval = outer.distance(domain, pos); + } + + virtual void operator()(cylindrical_single_type const& domain) const + { + retval = outer.distance(domain, pos); + } + + virtual void operator()(spherical_pair_type const& domain) const + { + retval = outer.distance(domain, pos); + } + + virtual void operator()(cylindrical_pair_type const& domain) const + { + retval = outer.distance(domain, pos); + } + + distance_visitor(EGFRDSimulator const& outer, position_type const& pos, + length_type& retval) + : outer(outer), pos(pos), retval(retval) {} + + EGFRDSimulator const& outer; + position_type const& pos; + length_type& retval; + }; + + domain.accept(distance_visitor(*this, pos, retval)); + return retval; + } + + boost::optional + form_pair(single_type& domain, single_type& possible_partner, + std::vector > const& neighbors) + { + LOG_DEBUG((""trying to form Pair(%s, %s)"", + boost::lexical_cast(domain).c_str(), + boost::lexical_cast(possible_partner).c_str())); + // 1. Determine min shell size. + length_type const r[] = { + domain.particle().second.radius(), + possible_partner.particle().second.radius() + }; + length_type const sigma(r[0] + r[1]); + + D_type const D[] = { + domain.particle().second.D(), + possible_partner.particle().second.D() + }; + D_type const D01(D[0] + D[1]); + + BOOST_ASSERT(domain.particle().second.position() == + domain.position()); + + BOOST_ASSERT(possible_partner.particle().second.position() == + possible_partner.position()); + + position_type iv( + subtract(domain.position(), + (*base_type::world_).periodic_transpose( + possible_partner.position(), + domain.position()))); + length_type const r0(length(iv)); + length_type const distance_from_sigma(r0 - sigma); + BOOST_ASSERT(distance_from_sigma >= 0); + + length_type const shell_size[] = { + r0 * D[0] / D01 + r[0], r0 * D[1] / D01 + r[1] + }; + length_type const shell_size_margin[] = { + r[0] * 2, + r[1] * 2 + }; + size_t const larger_shell_index( + shell_size[0] + shell_size_margin[0] >= + shell_size[1] + shell_size_margin[1] ? 0: 1); + length_type const min_shell_size(shell_size[larger_shell_index]); + length_type const min_shell_size_margin(shell_size_margin[larger_shell_index]); + + // 2. Check if min shell size not larger than max shell size or + // sim cell size. + position_type com((*base_type::world_).apply_boundary( + (*base_type::world_).calculate_pair_CoM( + domain.position(), possible_partner.position(), + D[0], D[1]))); + length_type const min_shell_size_with_margin( + min_shell_size + min_shell_size_margin); + length_type const max_shell_size( + std::min(this->max_shell_size(), + distance_from_sigma * 100 + + sigma + min_shell_size_margin)); + + if (min_shell_size_with_margin >= max_shell_size) + { + LOG_DEBUG((""Pair(%s, %s) not formed: min_shell_size %.16g >="" + ""max_shell_size %.16g"", + boost::lexical_cast(domain).c_str(), + boost::lexical_cast(possible_partner).c_str(), + min_shell_size_with_margin, max_shell_size)); + return boost::optional(); + } + + // 3. Check if bursted Singles not too close. + // The simple check for closest below could miss + // some of them, because sizes of these Singles for this + // distance check has to include SINGLE_SHELL_FACTOR, while + // these burst objects have zero mobility radii. This is not + // beautiful, a cleaner framework may be possible. + + domain_type* closest_domain (0); + length_type closest_shell_distance(std::numeric_limits::infinity()); + for (std::shared_ptr _neighbor: neighbors) + { + single_type* const neighbor( + dynamic_cast(_neighbor.get())); + if (neighbor && neighbor->id() != possible_partner.id()) + { + length_type const shell_distance( + (*base_type::world_).distance(com, neighbor->position()) - + neighbor->particle().second.radius() * + (1.0 + traits_type::SINGLE_SHELL_FACTOR)); + if (shell_distance < closest_shell_distance) + { + closest_domain = neighbor; + closest_shell_distance = shell_distance; + } + } + } + + if (closest_domain) + { + BOOST_ASSERT(closest_shell_distance > 0); + + if (closest_shell_distance <= min_shell_size_with_margin) + { + LOG_DEBUG((""Pair(%s, %s) not formed: squeezed by burst neighbor %s"", + boost::lexical_cast(domain).c_str(), + boost::lexical_cast(possible_partner).c_str(), + boost::lexical_cast(*closest_domain).c_str())); + return boost::optional(); + } + } + + // 4. Determine shell size and check if closest object not too + // close (squeezing). + { + std::pair possible_closest( + get_closest_domain(com, array_gen(domain.id(), + possible_partner.id()))); + if (possible_closest.second < closest_shell_distance) + { + domain_type* const _closest_domain( + get_domain(possible_closest.first).get()); + closest_domain = _closest_domain; + closest_shell_distance = possible_closest.second; + } + } + + if (closest_domain) + { + LOG_DEBUG((""Pair closest neighbor: %s %.16g, "" + ""min_shell_with_margin=%.16g"", + boost::lexical_cast(*closest_domain).c_str(), + closest_shell_distance, + min_shell_size_with_margin)); + BOOST_ASSERT(closest_shell_distance > 0); + } + + length_type new_shell_size(0.); + + { + single_type* const _closest_domain( + dynamic_cast(closest_domain)); + if (_closest_domain) + { + particle_type const& closest_domain_particle( + _closest_domain->particle().second); + D_type const D_tot(closest_domain_particle.D() + D01); + length_type const closest_particle_distance( + (*base_type::world_).distance( + com, closest_domain_particle.position())); + length_type const closest_min_shell( + closest_domain_particle.radius() * + (traits_type::SINGLE_SHELL_FACTOR + 1.0)); + + // options for shell size: + // a. ideal shell size + // b. closest shell is from a bursted single + // c. closest shell is closer than ideal shell size + new_shell_size = std::min( + std::min( + (D01 / D_tot) * ( + closest_particle_distance - min_shell_size + - closest_domain_particle.radius()) + + min_shell_size, + closest_particle_distance - closest_min_shell), + closest_shell_distance); + } + else + { + new_shell_size = closest_shell_distance; + } + new_shell_size /= traits_type::SAFETY; + + if (new_shell_size <= min_shell_size_with_margin) + { + LOG_DEBUG((""Pair(%s, %s) not formed%s%s"", + boost::lexical_cast(domain).c_str(), + boost::lexical_cast(possible_partner).c_str(), + closest_domain ? "": squeezed by "": """", + closest_domain ? boost::lexical_cast(*closest_domain).c_str(): """")); + return boost::optional(); + } + } + + // 5. Check if singles would not be better. + { + length_type const dist[] = { + (*base_type::world_).distance(com, domain.position()), + (*base_type::world_).distance(com, domain.position()) + }; + + if (new_shell_size < std::max( + dist[0] + r[0] * + (1.0 + traits_type::SINGLE_SHELL_FACTOR), + dist[1] + r[1] * + (1.0 + traits_type::SINGLE_SHELL_FACTOR)) * 1.3) + { + LOG_DEBUG((""Pair(%s, %s) not formed: leaving singles are better"", + boost::lexical_cast(domain).c_str(), + boost::lexical_cast(possible_partner).c_str())); + return boost::optional(); + } + } + + // 6. Ok, Pair makes sense. Create one. + new_shell_size = std::min(new_shell_size, max_shell_size); + + std::shared_ptr new_pair( + create_pair( + domain.particle(), + possible_partner.particle(), + com, iv, new_shell_size)); + + determine_next_event(*new_pair); + BOOST_ASSERT(new_pair->dt() >= 0); + + new_pair->last_time() = this->t(); + + remove_domain(domain); + remove_domain(possible_partner); + + BOOST_ASSERT( + (closest_domain && closest_shell_distance == + std::numeric_limits::infinity()) + || new_shell_size < closest_shell_distance); + BOOST_ASSERT(new_shell_size >= min_shell_size_with_margin); + BOOST_ASSERT(new_shell_size <= max_shell_size); + + LOG_INFO((""new_pair=%s, closest_shell_distance=%.16g, closest=%s"", + boost::lexical_cast(*new_pair).c_str(), + closest_shell_distance, + closest_domain ? boost::lexical_cast(closest_domain).c_str(): ""(none)"")); + + return *new_pair; + } + + boost::optional + form_multi(single_type& domain, + std::vector > const& neighbors, + std::pair closest) + { + // do not remove the return value specifier. Without this, you will + // encounter a problem like ""cannot allocate an object of abstract type"" + // because the default return type is `domain_type`. + const auto dereferencer = + [](const std::shared_ptr& ptr) -> const domain_type& { + return *ptr; + }; + // this lambda is defined out of the macro because passing lambda + // to macro causes a problem in some cases. + + LOG_DEBUG((""form multi: neighbors=[%s], closest=%s"", + stringize_and_join( + make_transform_iterator_range(neighbors, dereferencer), "", "" + ).c_str(), + boost::lexical_cast(*closest.first).c_str())); + length_type const min_shell_size( + domain.particle().second.radius() * + (1.0 + multi_shell_factor_)); + + // Multis shells need to be contiguous. + if (closest.second > min_shell_size) + { + LOG_DEBUG((""multi shells aren't close enough to each other (closest distance=%.16g, min_shell_size=%.16g)"", closest.second, min_shell_size)); + return boost::optional(); + } + + // If there's a multi neighbor, merge others into it. + // Otherwise, create a new multi and let it hold them all. + multi_type* retval(0); + retval = dynamic_cast(closest.first); + if (!retval) + { + retval = create_multi().get(); + add_event(*retval); + LOG_DEBUG((""form multi: created a new multi %s"", + boost::lexical_cast(*retval).c_str())); + } + + position_type const single_pos(domain.position()); + add_to_multi(*retval, domain); + + for (std::shared_ptr neighbor: neighbors) + { + length_type const dist(distance(*neighbor, single_pos)); + if (dist < min_shell_size) + add_to_multi_recursive(*retval, *neighbor); + } + + return *retval; + } + + bool add_to_multi(multi_type& multi, single_type& single) + { + LOG_DEBUG((""adding single to multi: %s => %s"", + boost::lexical_cast(single).c_str(), + boost::lexical_cast(multi).c_str())); + + if (!multi.add_particle(single.particle())) + { + LOG_DEBUG((""particle %s is already added to %s"", + boost::lexical_cast(single.particle().first).c_str(), + boost::lexical_cast(multi).c_str())); + return false; + } + + spherical_shell_id_pair sid_shell_pair( + new_shell( + multi.id(), + typename spherical_shell_type::shape_type( + single.particle().second.position(), + single.particle().second.radius() * + (1. + multi_shell_factor_)))); + multi.add_shell(sid_shell_pair); + remove_domain(single); + return true; + } + + void add_to_multi(multi_type& multi, multi_type& other_multi) + { + if (multi.id() == other_multi.id()) + { + LOG_DEBUG((""add multi to multi: given two multis are the same; do nothing"")); + return; + } + if (multi.has_particle(other_multi.get_particles_range().front().first)) + { + LOG_DEBUG((""add multi to multi: given multi already added."")); + return; + } + + LOG_DEBUG((""adding multi to multi: %s => %s"", + boost::lexical_cast(other_multi).c_str(), + boost::lexical_cast(multi).c_str())); + + // merge other_multi into multi. other_multi will be removed. + spherical_shell_matrix_type& mat( + *boost::fusion::at_key(smatm_)); + for (spherical_shell_id_pair const& _shell: + other_multi.get_shells()) + { + typename spherical_shell_matrix_type::iterator const i( + mat.find(_shell.first)); + BOOST_ASSERT(i != mat.end()); + spherical_shell_type& shell((*i).second); + shell.did() = multi.id(); + multi.add_shell(spherical_shell_id_pair(_shell.first, shell)); + } + + for (particle_id_pair const& particle: + other_multi.get_particles_range()) + { + multi.add_particle(particle); + } + + remove_domain_but_shell(other_multi); + } + + void add_to_multi_recursive(multi_type& multi, domain_type& domain) + { + LOG_DEBUG((""add_to_multi_recursive: multi=%s, domain=%s"", + boost::lexical_cast(multi).c_str(), + boost::lexical_cast(domain).c_str())); + { + single_type* single(dynamic_cast(&domain)); + if (single) + { + particle_shape_type const new_shell( + single->particle().second.position(), + single->particle().second.radius() * + (1.0 + multi_shell_factor_)); + + if (!add_to_multi(multi, *single)) + { + return; + } + + std::unique_ptr > neighbors( + get_neighbor_domains(new_shell, single->id())); + + std::vector > bursted; + burst_non_multis(*neighbors, bursted); + + // do not remove the return value specifier. Without this, you + // will encounter a problem like ""cannot allocate an object of + // abstract type"" because the default return type is `domain_type`. + const auto dereferencer = + [](const std::shared_ptr& ptr) + -> const domain_type& { + return *ptr; + }; + // this lambda is defined out of the macro because passing lambda + // to macro causes a problem in some cases. + + LOG_DEBUG((""add_to_multi_recursive: bursted=[%s]"", + stringize_and_join( + make_transform_iterator_range(bursted, dereferencer), + "", "").c_str())); + + for (std::shared_ptr neighbor: bursted) + { + length_type const dist(distance(*neighbor, single->position())); + if (dist < new_shell.radius()) + add_to_multi_recursive(multi, *neighbor); + } + return; + } + } + { + multi_type* other_multi(dynamic_cast(&domain)); + if (other_multi) + { + add_to_multi(multi, *other_multi); + } + } + } + + boost::optional form_pair_or_multi( + single_type& domain, + std::vector > const& neighbors) + { + BOOST_ASSERT(!neighbors.empty()); + + domain_type* possible_partner(0); + length_type length_to_possible_partner( + std::numeric_limits::infinity()); + for (std::shared_ptr neighbor: neighbors) + { + length_type const dist(distance(*neighbor, domain.position())); + if (dist < length_to_possible_partner) + { + possible_partner = neighbor.get(); + length_to_possible_partner = dist; + } + } + + // First, try forming a Pair. + { + single_type* const _possible_partner( + dynamic_cast(possible_partner)); + if (_possible_partner) + { + boost::optional new_pair( + form_pair(domain, *_possible_partner, neighbors)); + if (new_pair) + { + return new_pair.get(); + } + } + } + + // If a Pair is not formed, then try forming a Multi. + { + boost::optional new_multi( + form_multi(domain, neighbors, + std::pair( + possible_partner, + length_to_possible_partner))); + if (new_multi) + { + return new_multi.get(); + } + } + return boost::optional(); + } + + void fire_event(single_event const& event) + { + single_type& domain(event.domain()); +#if 0 + BOOST_ASSERT( + std::abs(domain.dt() + domain.last_time() - this->t()) + <= 1e-18 * this->t()); +#endif + ++single_step_count_[event.kind()]; + switch (event.kind()) + { + default: /* never get here */ BOOST_ASSERT(0); break; + case SINGLE_EVENT_REACTION: + LOG_DEBUG((""fire_single: single reaction (%s)"", boost::lexical_cast(domain).c_str())); + propagate(domain, draw_new_position(domain, domain.dt()), false); + try + { + attempt_single_reaction(domain); + } + catch (NoSpace const&) + { + LOG_DEBUG((""single reaction rejected"")); + ++rejected_moves_; + domain.dt() = 0.; + domain.last_time() = this->t(); + add_event(domain, SINGLE_EVENT_ESCAPE); + } + break; + + case SINGLE_EVENT_ESCAPE: + LOG_DEBUG((""fire_single: single escape (%s)"", boost::lexical_cast(domain).c_str())); + + // handle immobile case + if (domain.D() == 0.) + { + determine_next_event(domain); + domain.last_time() = this->t(); + return; + } + + if (domain.dt() != 0.) + // Heads up: shell matrix will be updated later in restore_domain(). + // propagate(domain, draw_new_position(domain, domain.dt()), false); + propagate(domain, draw_escape_position(domain), false); + length_type const min_shell_radius(domain.particle().second.radius() * (1. + single_shell_factor_)); + { + std::vector* intruders; + std::pair closest; + + // boost::tie(intruders, closest) = get_intruders( + // particle_shape_type( + // domain.position(), min_shell_radius), domain.id()); + { + std::pair*, + std::pair > + res(get_intruders(particle_shape_type( + domain.position(), + min_shell_radius), + domain.id())); + intruders = res.first; + closest = res.second; + } + + std::unique_ptr > _(intruders); + + LOG_DEBUG((""intruders: %s, closest: %s (dist=%.16g)"", + intruders ? + stringize_and_join(*intruders, "", "").c_str(): + ""(none)"", + boost::lexical_cast(closest.first).c_str(), + closest.second)); + if (intruders) + { + std::vector > bursted; + burst_non_multis(*intruders, bursted); + if (form_pair_or_multi(domain, bursted)) + return; + // if nothing was formed, recheck closest and restore shells. + restore_domain(domain); + for (std::shared_ptr _single: bursted) + { + std::shared_ptr single( + std::dynamic_pointer_cast(_single)); + if (!single) + continue; + restore_domain(*single); + // reschedule events for the restored domains + remove_event(*single); + determine_next_event(*single); + } + } else { + restore_domain(domain, closest); + } + determine_next_event(domain); + LOG_DEBUG((""%s (dt=%.16g)"", + boost::lexical_cast(domain).c_str(), + domain.dt())); + } + } + } + + template + greens_functions::GreensFunction3DRadAbs::EventKind + draw_iv_event_type(AnalyticalPair const& domain) + { + typedef Tshell shell_type; + typedef typename shell_type::shape_type shape_type; + typedef typename detail::get_pair_greens_function::iv_type iv_greens_function; + // Draw actual pair event for iv at very last minute. + BOOST_ASSERT(ecell4::egfrd::size(domain.reactions()) == 1); + reaction_rule_type const& r(domain.reactions()[0]); + iv_greens_function const gf(domain.D_tot(), r.k(), domain.r0(), domain.sigma(), domain.a_r()); + + double const rnd(this->rng().uniform(0, 1.)); + return gf.drawEventType(rnd, domain.dt()); + } + + void fire_event(pair_event const& event) + { + { + spherical_pair_type* _domain(dynamic_cast(&event.domain())); + if (_domain) + { + fire_event(*_domain, event.kind()); + return; + } + } + { + cylindrical_pair_type* _domain(dynamic_cast(&event.domain())); + if (_domain) + { + fire_event(*_domain, event.kind()); + return; + } + } + } + + template + void fire_event(AnalyticalPair& domain, pair_event_kind kind) + { + // typedef AnalyticalSingle corresponding_single_type; + + if (kind == PAIR_EVENT_IV_UNDETERMINED) + { + // Draw actual pair event for iv at very last minute. + switch (draw_iv_event_type(domain)) + { + case greens_functions::GreensFunction3DRadAbs::IV_ESCAPE: + kind = PAIR_EVENT_IV_ESCAPE; + break; + case greens_functions::GreensFunction3DRadAbs::IV_REACTION: + kind = PAIR_EVENT_IV_REACTION; + break; + } + } + + ++pair_step_count_[kind]; + LOG_DEBUG((""fire_pair: %s"", stringize_event_kind(kind).c_str())); + + // 1. Single reaction + // 2. Pair reaction + // 3a. IV escape + // 3b. com escape + + switch (kind) + { + default: /* never get here */ BOOST_ASSERT(0); break; + case PAIR_EVENT_SINGLE_REACTION_0: + case PAIR_EVENT_SINGLE_REACTION_1: + { + int const index(kind == PAIR_EVENT_SINGLE_REACTION_0 ? 0 : 1); + // TODO. + //int const theother_index(1 - index); + position_type const old_CoM(domain.position()); + LOG_DEBUG((""pair: single reaction %s"", boost::lexical_cast(domain.particles()[index].first).c_str())); + + std::array, 2> const new_single(burst(domain)); + + try + { + attempt_single_reaction(*new_single[index]); + } + catch (NoSpace const&) + { + LOG_DEBUG((""pair event single reaction rejected"")); + ++rejected_moves_; + } + } + break; + + case PAIR_EVENT_COM_ESCAPE: + { + LOG_DEBUG((""=> com_escape"")); + time_type const dt(domain.dt()); + std::array const new_pos( + draw_new_positions( + domain, dt)); + std::array, 2> const new_single( + propagate(domain, new_pos)); + + add_event(*new_single[0], SINGLE_EVENT_ESCAPE); + add_event(*new_single[1], SINGLE_EVENT_ESCAPE); + } + break; + + case PAIR_EVENT_IV_REACTION: + { + LOG_DEBUG((""=> iv_reaction"")); + + BOOST_ASSERT(ecell4::egfrd::size(domain.reactions()) >= 1); +// reaction_rule_type const& r(domain.reactions()[0]); + + Real k_tot = 0; + for(reaction_rule_type const& rl: domain.reactions()) + { + k_tot += rl.k(); + } + + boost::optional optr(boost::none); + if(ecell4::egfrd::size(domain.reactions()) != 1) + { + Real rndr = this->rng().uniform(0., k_tot); + for(reaction_rule_type const& rl: domain.reactions()) + { + rndr -= rl.k(); + if(rndr < 0.0) + { + optr = rl; + break; + } + } + // optr maybe empty because of numerical error. in that case, + // use domain.reactants().back(). + // if domain.reactions().size() == 1, it is okay to use + // domain.reactants().back() because it is the only rule + // that can be applied. + } + reaction_rule_type const& r = + (static_cast(optr)) ? *optr : domain.reactions().back(); + + switch (ecell4::egfrd::size(r.get_products())) + { + case 0: + { + (*base_type::world_).remove_particle(domain.particles()[0].first); + (*base_type::world_).remove_particle(domain.particles()[1].first); + if (base_type::rrec_) + { + (*base_type::rrec_)(reaction_record_type( + r.id(), + array_gen(), + domain.particles()[0], + domain.particles()[1])); + } + } + break; + case 1: + { + species_id_type const& new_species_id(r.get_products()[0]); + molecule_info_type const new_species( + (*base_type::world_).get_molecule_info(new_species_id)); + + // calculate new R + position_type const new_com( + (*base_type::world_).apply_boundary( + draw_on_iv_reaction( + this->rng(), + *base_type::world_).draw_com( + domain, domain.dt()))); + + BOOST_ASSERT( + (*base_type::world_).distance( + domain.shell().second.position(), + new_com) + new_species.radius + < shape(domain.shell().second).radius()); + + (*base_type::world_).remove_particle(domain.particles()[0].first); + (*base_type::world_).remove_particle(domain.particles()[1].first); + + particle_id_pair const new_particle( + (*base_type::world_).new_particle( + new_species_id, new_com).first); + std::shared_ptr new_single( + create_single(new_particle)); + add_event(*new_single, SINGLE_EVENT_ESCAPE); + + if (base_type::rrec_) + { + // (*base_type::rrec_)(reaction_record_type( + // r.id(), + // array_gen(new_particle.first), + // domain.particles()[0].first, + // domain.particles()[1].first)); + (*base_type::rrec_)(reaction_record_type( + r.id(), + array_gen(new_particle), + domain.particles()[0], + domain.particles()[1])); + } + } + break; + default: + throw ::ecell4::NotImplemented(""num products >= 2 not supported.""); + } + remove_domain(domain); + } + break; + case PAIR_EVENT_IV_ESCAPE: + { + LOG_DEBUG((""=> iv_escape"")); + time_type const dt(domain.dt()); + std::array const new_pos( + draw_new_positions( + domain, dt)); + std::array, 2> const new_single( + propagate(domain, new_pos)); + + add_event(*new_single[0], SINGLE_EVENT_ESCAPE); + add_event(*new_single[1], SINGLE_EVENT_ESCAPE); + } + break; + } + } + + void fire_event(multi_event& event) + { + multi_type& domain(event.domain()); + domain.step(); + LOG_DEBUG((""fire_multi: last_event=%s"", boost::lexical_cast(domain.last_event()).c_str())); + multi_step_count_[domain.last_event()]++; + switch (domain.last_event()) + { + default: /* never get here */ BOOST_ASSERT(0); break; + case multi_type::REACTION: + if (base_type::rrec_) + (*base_type::rrec_)(domain.last_reaction()); + burst(domain); + break; + case multi_type::ESCAPE: + burst(domain); + break; + case multi_type::NONE: + add_event(domain); + break; + } + } + + void fire_event(birth_event& event) + { + const reaction_rule_type& rr(event.reaction_rule()); + BOOST_ASSERT(ecell4::egfrd::size(rr.get_products())); + species_id_type const& sp(rr.get_products()[0]); + LOG_DEBUG((""fire_birth: product=%s"", boost::lexical_cast(sp).c_str())); + + try + { + molecule_info_type const minfo( + (*base_type::world_).get_molecule_info(sp)); + + position_type new_pos; + const unsigned int max_retry_position = 1000; // 1 means no retry. + for (unsigned int i = 0; i < max_retry_position; ++i) + { + //XXX: A cuboidal region is expected here. + new_pos[0] = this->rng().uniform(0, (*base_type::world_).edge_lengths()[0]); + new_pos[1] = this->rng().uniform(0, (*base_type::world_).edge_lengths()[1]); + new_pos[2] = this->rng().uniform(0, (*base_type::world_).edge_lengths()[2]); + + const particle_shape_type new_particle(new_pos, minfo.radius); + + clear_volume(new_particle); + + if (!(*base_type::world_).no_overlap(new_particle)) + { + if (i != max_retry_position - 1) + { + continue; + } + LOG_INFO((""no space for product particle."")); + throw NoSpace(); + } + else + { + break; + } + } + + particle_id_pair pp( + (*base_type::world_).new_particle(sp, new_pos).first); + + if (base_type::rrec_) + { + (*base_type::rrec_)( + reaction_record_type(rr.id(), array_gen(pp))); + } + + std::shared_ptr single(create_single(pp)); + add_event(*single, SINGLE_EVENT_ESCAPE); + } + catch (NoSpace const&) + { + LOG_DEBUG((""birth reaction rejected."")); + ++rejected_moves_; + } + + add_event(rr); + } + + void fire_event(event_type& event) + { + { + single_event* _event(dynamic_cast(&event)); + if (_event) + { + fire_event(*_event); + return; + } + } + { + pair_event* _event(dynamic_cast(&event)); + if (_event) + { + fire_event(*_event); + return; + } + } + { + multi_event* _event(dynamic_cast(&event)); + if (_event) + { + fire_event(*_event); + return; + } + } + { + birth_event* _event(dynamic_cast(&event)); + if (_event) + { + fire_event(*_event); + return; + } + } + throw ::ecell4::NotImplemented(std::string(""unsupported domain type"")); + } + + void _step() + { + if (base_type::paranoiac_) + BOOST_ASSERT(check()); + + ++base_type::num_steps_; + + (*dynamic_cast*>( + base_type::rrec_.get())).clear(); + + if (scheduler_.size() == 0) + { + this->set_t(scheduler_.next_time()); + return; + } + + event_id_pair_type ev(scheduler_.pop()); + this->set_t(ev.second->time()); + + LOG_INFO((""%d: t=%.16g dt=%.16g domain=%s rejectedmoves=%d"", + base_type::num_steps_, this->t(), base_type::dt_, + boost::lexical_cast(dynamic_cast(ev.second.get())->domain()).c_str(), + rejected_moves_)); + + fire_event(*ev.second); + + time_type const next_time(scheduler_.top().second->time()); + base_type::dt_ = next_time - this->t(); + + if (base_type::dt_ == 0.) + { + ++zero_step_count_; + if (zero_step_count_ >= std::max(scheduler_.size() * 3, static_cast(10u))) + { + throw ::ecell4::IllegalState(""too many dt=zero steps. simulator halted?""); + } + } + else + { + zero_step_count_ = 0; + } + } + + static domain_kind get_domain_kind(domain_type const& domain) + { + struct domain_kind_visitor: ImmutativeDomainVisitor + { + virtual ~domain_kind_visitor() {} + + virtual void operator()(multi_type const&) const + { + retval = MULTI; + } + + virtual void operator()(spherical_single_type const&) const + { + retval = SPHERICAL_SINGLE; + } + + virtual void operator()(cylindrical_single_type const&) const + { + retval = CYLINDRICAL_SINGLE; + } + + virtual void operator()(spherical_pair_type const&) const + { + retval = SPHERICAL_PAIR; + } + + virtual void operator()(cylindrical_pair_type const&) const + { + retval = CYLINDRICAL_PAIR; + } + + domain_kind_visitor(domain_kind& retval): retval(retval) {} + + domain_kind& retval; + }; + + domain_kind retval = NONE; + domain.accept(domain_kind_visitor(retval)); + return retval; + } + + static domain_kind get_domain_kind(spherical_single_type const&) + { + return SPHERICAL_SINGLE; + } + + static domain_kind get_domain_kind(cylindrical_single_type const&) + { + return CYLINDRICAL_SINGLE; + } + + static domain_kind get_domain_kind(spherical_pair_type const&) + { + return SPHERICAL_PAIR; + } + + static domain_kind get_domain_kind(cylindrical_pair_type const&) + { + return CYLINDRICAL_PAIR; + } + + static domain_kind get_domain_kind(multi_type const&) + { + return MULTI; + } + + void dump_events() const + { + LOG_INFO((""QUEUED EVENTS:"")); + for (event_id_pair_type const& ev: scheduler_.events()) + { + LOG_INFO(("" #%d: %s"", ev.first, stringize_event(*ev.second).c_str())); + } + } + + static std::string stringize_event(event_type const& ev) + { + { + single_event const* _ev(dynamic_cast(&ev)); + if (_ev) + { + return stringize_event(*_ev); + } + } + { + pair_event const* _ev(dynamic_cast(&ev)); + if (_ev) + { + return stringize_event(*_ev); + } + } + { + multi_event const* _ev(dynamic_cast(&ev)); + if (_ev) + { + return stringize_event(*_ev); + } + } + return (boost::format(""Event(t=%.16g)"") % ev.time()).str(); + } + + static std::string stringize_event_kind(enum single_event_kind kind) + { + switch (kind) + { + default: /* never get here */ BOOST_ASSERT(0); break; + case SINGLE_EVENT_ESCAPE: + return ""escape""; + + case SINGLE_EVENT_REACTION: + return ""reaction""; + } + } + + static std::string stringize_event_kind(enum pair_event_kind kind) + { + switch (kind) + { + default: /* never get here */ BOOST_ASSERT(0); break; + case PAIR_EVENT_SINGLE_REACTION_0: + return ""reaction(0)""; + + case PAIR_EVENT_SINGLE_REACTION_1: + return ""reaction(1)""; + + case PAIR_EVENT_COM_ESCAPE: + return ""com_escape""; + + case PAIR_EVENT_IV_UNDETERMINED: + return ""iv_undetermined""; + + case PAIR_EVENT_IV_ESCAPE: + return ""iv_escape""; + + case PAIR_EVENT_IV_REACTION: + return ""iv_reaction""; + } + throw ::ecell4::IllegalState(""EGFRDSimulator::stringize_event_kind: never get here""); + } + + static std::string stringize_event(single_event const& ev) + { + return (boost::format(""SingleEvent(t=%.16g, kind=%s, domain=%s)"") % + ev.time() % stringize_event_kind(ev.kind()) % + boost::lexical_cast(ev.domain())).str(); + } + + static std::string stringize_event(pair_event const& ev) + { + return (boost::format(""PairEvent(t=%.16g, kind=%s, domain=%s)"") % + ev.time() % stringize_event_kind(ev.kind()) % + boost::lexical_cast(ev.domain())).str(); + } + + static std::string stringize_event(multi_event const& ev) + { + return (boost::format(""MultiEvent(t=%.16g, domain=%s)"") % + ev.time() % boost::lexical_cast(ev.domain())).str(); + } + + template + bool check_domain(AnalyticalSingle const& domain) const + { + LOG_DEBUG((""checking domain %s"", boost::lexical_cast(domain).c_str())); + bool retval(true); + std::pair closest( + get_closest_domain(domain.position(), array_gen(domain.id()))); + CHECK(shape_size(shape(domain.shell().second)) <= user_max_shell_size_); + CHECK(shape_size(shape(domain.shell().second)) <= max_shell_size()); + CHECK(closest.second > shape_size(shape(domain.shell().second))); + return retval; + } + + template + bool check_domain(AnalyticalPair const& domain) const + { + LOG_DEBUG((""checking domain %s"", boost::lexical_cast(domain).c_str())); + bool retval(true); + std::pair closest( + get_closest_domain(domain.position(), array_gen(domain.id()))); + CHECK(shape_size(shape(domain.shell().second)) <= user_max_shell_size_); + CHECK(shape_size(shape(domain.shell().second)) <= max_shell_size()); + CHECK(closest.second > shape_size(shape(domain.shell().second))); + return retval; + } + + bool check_domain(multi_type const& domain) const + { + LOG_DEBUG((""checking domain %s"", boost::lexical_cast(domain).c_str())); + bool retval(true); + for (typename multi_type::spherical_shell_id_pair const& shell: + domain.get_shells()) + { + std::pair closest( + get_closest_domain(shape_position(shape(shell.second)), + array_gen(domain.id()))); + CHECK(shape_size(shape(shell.second)) <= user_max_shell_size_); + CHECK(shape_size(shape(shell.second)) <= max_shell_size()); + CHECK(closest.second > shape_size(shape(shell.second))); + } + return retval; + } + + bool check_domain(domain_type const& domain) const + { + struct visitor: public ImmutativeDomainVisitor + { + virtual ~visitor() {} + + virtual void operator()(multi_type const& domain) const + { + retval = self.check_domain(domain); + } + + virtual void operator()(spherical_single_type const& domain) const + { + retval = self.check_domain(domain); + } + + virtual void operator()(cylindrical_single_type const& domain) const + { + retval = self.check_domain(domain); + } + + virtual void operator()(spherical_pair_type const& domain) const + { + retval = self.check_domain(domain); + } + + virtual void operator()(cylindrical_pair_type const& domain) const + { + retval = self.check_domain(domain); + } + + visitor(EGFRDSimulator const& self, bool& retval) + : self(self), retval(retval) {} + + EGFRDSimulator const& self; + bool& retval; + }; + + bool retval; + domain.accept(visitor(*this, retval)); + return retval; + } + + bool check_overlap(particle_shape_type const& s) const + { + const particle_id_pair_and_distance_list overlapped( + (*base_type::world_).check_overlap(s)); + + if (overlapped.size() > 0) + { + LOG_DEBUG((""check_overlap %s failed:"", + boost::lexical_cast(s).c_str())); + dump_overlapped(overlapped); + return false; + } + return true; + } + + bool check_overlap(particle_shape_type const& s, particle_id_type const& ignore) const + { + const particle_id_pair_and_distance_list overlapped( + (*base_type::world_).check_overlap(s, ignore)); + + if (overlapped.size() > 0) + { + LOG_DEBUG((""check_overlap %s failed:"", + boost::lexical_cast(s).c_str()); + dump_overlapped(overlapped)); + return false; + } + return true; + } + + bool check_overlap(particle_shape_type const& s, particle_id_type const& ignore1, particle_id_type const& ignore2) const + { + const particle_id_pair_and_distance_list overlapped( + (*base_type::world_).check_overlap(s, ignore1, ignore2)); + + if (overlapped.size() > 0) + { + LOG_DEBUG((""check_overlap %s failed:"", + boost::lexical_cast(s).c_str())); + dump_overlapped(overlapped); + return false; + } + return true; + } + + void dump_overlapped(particle_id_pair_and_distance_list const& list)const + { + if (log_.level() == Logger::L_DEBUG) + { + for (particle_id_pair_and_distance const& i: list) + { + log_.debug("" (%s:%s) %.16g"", + boost::lexical_cast(i.first.first).c_str(), + boost::lexical_cast(i.first.second).c_str(), + i.second); + } + } + } + + static rate_type calculate_k_tot(reaction_rules const& rules) + { + rate_type k_tot(0.); + for (reaction_rule_type const& rule: rules) + { + k_tot += rule.k(); + } + return k_tot; + } + + reaction_rule_type const& draw_reaction_rule(reaction_rules const& rules) + { + const rate_type k_tot(calculate_k_tot(rules)); + if(k_tot == std::numeric_limits::infinity()) + { + LOG_WARNING((""k_tot == infinite: first reaction type applied."")); + return rules[0]; + } + + const rate_type t(this->rng().uniform(0., 1.) * k_tot); + rate_type a(0.); + for(reaction_rule_type const& r: rules) + { + a += r.k(); + if (a > t) + return r; + } + + BOOST_ASSERT(false); // should never happen + throw ::ecell4::IllegalState(""EGFRDSimulator::draw_reaction_rule: should never happen""); + } + + //template + static position_type + //adjust_iv_with_old_iv(T1 const& new_iv, T2 const& old_iv) + adjust_iv_with_old_iv(position_type const& new_iv, position_type const& old_iv) + { + length_type const angle(std::acos(old_iv[2] / length(old_iv))); + if (std::fmod(angle, M_PI) != 0.0) + { + position_type const rotation_axis( + normalize(position_type(-old_iv[1], old_iv[0], 0.))); + return rotate_vector(new_iv, rotation_axis, angle); + } + else if (angle == 0.) + { + return new_iv; + } + else + { + return position_type(new_iv[0], new_iv[1], -new_iv[1]); + } + } + + template + bool check_pair_pos(AnalyticalPair const& domain, + std::array const& new_particles) + { + length_type const new_distance( + (*base_type::world_).distance(new_particles[0].second.position(), + new_particles[1].second.position())); + length_type const r01(new_particles[0].second.radius() + + new_particles[1].second.radius()); + + if (new_distance <= r01) + { + log_.warn( + ""rejected move: pair=%s, radii=%.16g, particle_distance=%.16g"", + boost::lexical_cast(domain).c_str(), + r01, new_distance); + return false; + } + + // particles within mobility radius. + position_type const& com(shape(domain.shell().second).position()); + length_type const radius(shape(domain.shell().second).radius()); + length_type const d[2] = { + (*base_type::world_).distance(com, new_particles[0].second.position()) + new_particles[0].second.radius(), + (*base_type::world_).distance(com, new_particles[1].second.position()) + new_particles[1].second.radius() + }; + if (d[0] > radius || d[1] > radius) + { + log_.warn( + ""rejected move: new particle(s) out of protective sphere: pair=%s, radii=%.16g, d0=%.16g, d1=%.16g"", + boost::lexical_cast(domain).c_str(), + d[0], d[1]); + return false; + } + return true; + } + + template + static greens_functions::PairGreensFunction* choose_pair_greens_function( + AnalyticalPair const& domain, time_type t) + { + length_type const r0(domain.r0()); + length_type const distance_from_sigma(r0 - domain.sigma()); + length_type const distance_from_shell(domain.a_r() - r0); + length_type const threshold_distance( + traits_type::CUTOFF_FACTOR * std::sqrt(6. * domain.D_tot() * t)); + + BOOST_ASSERT(ecell4::egfrd::size(domain.reactions()) == 1); + if (distance_from_sigma < threshold_distance) + { + if (distance_from_shell < threshold_distance) + { + // near both a and sigma; + // use greens_functions::GreensFunction3DRadAbs + LOG_DEBUG((""GF: normal"")); + return new greens_functions::GreensFunction3DRadAbs( + domain.D_tot(), domain.reactions()[0].k(), + r0, domain.sigma(), domain.a_r()); + } + else + { + // near sigma; use greens_functions::GreensFunction3DRadInf + LOG_DEBUG((""GF: only sigma"")); + return new greens_functions::GreensFunction3DRadInf( + domain.D_tot(), domain.reactions()[0].k(), + r0, domain.sigma()); + } + } + else + { + if (distance_from_shell < threshold_distance) + { + // near a; + LOG_DEBUG((""GF: only a"")); + return new greens_functions::GreensFunction3DAbs( + domain.D_tot(), r0, domain.a_r()); + } + else + { + // distant from both a and sigma; + LOG_DEBUG((""GF: free"")); + return new greens_functions::GreensFunction3D(domain.D_tot(), r0); + } + } + } + + static length_type calculate_single_shell_size( + single_type const& single, + single_type const& closest, + length_type distance, + length_type shell_distance) + { + length_type const min_radius0(single.particle().second.radius()); + D_type const D0(single.particle().second.D()); + if (D0 == 0) + return min_radius0; + length_type const min_radius1(closest.particle().second.radius()); + D_type const D1(closest.particle().second.D()); + length_type const min_radius01(min_radius0 + min_radius1); + length_type const sqrtD0(std::sqrt(D0)); + + return std::max(std::min(sqrtD0 / (sqrtD0 + std::sqrt(D1)) + * (distance - min_radius01) + min_radius0, + shell_distance / traits_type::SAFETY), + min_radius0); + } + +protected: + double const bd_dt_factor_; + int const num_retries_; + length_type const user_max_shell_size_; + + domain_map domains_; + std::unique_ptr ssmat_; + std::unique_ptr csmat_; + shell_matrix_map_type smatm_; + shell_id_generator shidgen_; + domain_id_generator didgen_; + event_scheduler_type scheduler_; + std::array single_step_count_; + std::array pair_step_count_; + std::array multi_step_count_; + std::array domain_count_per_type_; + length_type single_shell_factor_; + length_type multi_shell_factor_; + unsigned int rejected_moves_; + unsigned int zero_step_count_; + bool dirty_; + static Logger& log_; +}; +#undef CHECK + +template +inline char const* retrieve_domain_type_name( + typename EGFRDSimulator::spherical_single_type const&) +{ + return ""SphericalSingle""; +} + +template +inline char const* retrieve_domain_type_name( + typename EGFRDSimulator::cylindrical_single_type const&) +{ + return ""CylindricalSingle""; +} + +template +inline char const* retrieve_domain_type_name( + typename EGFRDSimulator::spherical_pair_type const&) +{ + return ""SphericalPair""; +} + +template +inline char const* retrieve_domain_type_name( + typename EGFRDSimulator::cylindrical_pair_type const&) +{ + return ""CylindricalPair""; +} + + + +template +Logger& EGFRDSimulator::log_(Logger::get_logger(""ecell.EGFRDSimulator"")); + +} // egfrd +} // ecell4 +#endif /* EGFRDSIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Pair.hpp",".hpp","1538","63","#ifndef ECELL4_EGFRD_PAIR_HPP +#define ECELL4_EGFRD_PAIR_HPP + +#include +#include +#include +#include ""ShapedDomain.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +template +class Pair: public ShapedDomain +{ +public: + typedef ShapedDomain base_type; + typedef Ttraits_ traits_type; + typedef typename traits_type::world_type::particle_id_type particle_id_type; + typedef typename traits_type::world_type::particle_id_pair particle_id_pair; + typedef typename traits_type::domain_id_type identifier_type; + typedef std::array particle_array_type; + typedef typename traits_type::world_type::length_type length_type; + typedef typename traits_type::world_type::traits_type::position_type position_type; + +public: + virtual ~Pair() {} + + Pair(identifier_type const& id, + particle_id_pair const& p0, particle_id_pair const& p1) + : base_type(id) + { + if (p0.second.D() < p1.second.D()) + { + new(&particles_[0]) particle_id_pair(p0); + new(&particles_[1]) particle_id_pair(p1); + } + else + { + new(&particles_[0]) particle_id_pair(p1); + new(&particles_[1]) particle_id_pair(p0); + } + } + + particle_array_type const& particles() const + { + return particles_; + } + + particle_array_type& particles() + { + return particles_; + } + +protected: + particle_array_type particles_; +}; + +} // egfrd +} // ecell4 +#endif /* PAIR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ConsoleAppender.hpp",".hpp","801","39","#ifndef ECELL4_EGFRD_CONSOLE_LOGGER_HPP +#define ECELL4_EGFRD_CONSOLE_LOGGER_HPP +#include ""Logger.hpp"" +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +class ConsoleAppender: public LogAppender +{ +public: + typedef LogAppender base_type; + +public: + ~ConsoleAppender() override = default; + + void flush() override + { + std::fflush(stderr); + } + + void operator()(enum Logger::level lv, char const* name, char const** chunks) override + { + std::fprintf(stderr, ""%s: %-8s "", name, Logger::stringize_error_level(lv)); + for (char const** p = chunks; *p; ++p) + { + std::fwrite(*p, sizeof(char), std::strlen(*p), stderr); + } + std::fputc('\n', stderr); + } +}; + +} // egfrd +} // ecell4 +#endif /* CONSOLE_LOGGER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ParticleContainer.hpp",".hpp","4204","119","#ifndef ECELL4_EGFRD_PARTICLE_CONTAINER_HPP +#define ECELL4_EGFRD_PARTICLE_CONTAINER_HPP + +#include +#include + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +class ParticleContainer + : public ecell4::WorldInterface +{ +public: + + typedef Ttraits_ traits_type; + + typedef typename traits_type::particle_type particle_type; + typedef typename traits_type::particle_shape_type particle_shape_type; + typedef typename traits_type::molecule_info_type molecule_info_type; + typedef typename traits_type::species_id_type species_id_type; + typedef typename traits_type::position_type position_type; + typedef typename traits_type::particle_id_type particle_id_type; + typedef typename traits_type::length_type length_type; + typedef typename traits_type::size_type size_type; + typedef typename traits_type::time_type time_type; + typedef typename traits_type::structure_id_type structure_id_type; + typedef typename traits_type::structure_type structure_type; + typedef typename traits_type::particle_id_pair particle_id_pair; + typedef typename traits_type::particle_id_pair_generator + particle_id_pair_generator; + typedef typename traits_type::particle_id_pair_and_distance + particle_id_pair_and_distance; + typedef typename traits_type::particle_id_pair_and_distance_list + particle_id_pair_and_distance_list; + +public: + + virtual ~ParticleContainer() {}; + + virtual molecule_info_type get_molecule_info(species_id_type const& id) const = 0; + // virtual molecule_info_type const& get_molecule_info(species_id_type const& id) = 0; + // virtual molecule_info_type const& find_molecule_info(species_id_type const& id) const = 0; + + virtual std::shared_ptr get_structure( + structure_id_type const& id) const = 0; + + virtual std::pair new_particle( + species_id_type const& sid, position_type const& pos) = 0; + + virtual particle_id_pair_and_distance_list check_overlap( + particle_shape_type const& s) const = 0; + + virtual particle_id_pair_and_distance_list check_overlap( + particle_shape_type const& s, particle_id_type const& ignore) const = 0; + + virtual particle_id_pair_and_distance_list check_overlap( + particle_shape_type const& s, particle_id_type const& ignore1, + particle_id_type const& ignore2) const = 0; + + virtual bool no_overlap(particle_shape_type const& s) const + { + const particle_id_pair_and_distance_list overlapped( + check_overlap(s)); + return (overlapped.size() == 0); + } + + virtual bool no_overlap(particle_shape_type const& s, + particle_id_type const& ignore) const + { + const particle_id_pair_and_distance_list overlapped( + check_overlap(s, ignore)); + return (overlapped.size() == 0); + } + + virtual bool no_overlap(particle_shape_type const& s, + particle_id_type const& ignore1, particle_id_type const& ignore2) const + { + const particle_id_pair_and_distance_list overlapped( + check_overlap(s, ignore1, ignore2)); + return (overlapped.size() == 0); + } + + virtual bool update_particle(const particle_id_type& pid, const particle_type& p) = 0; + + virtual position_type periodic_transpose( + position_type const& p0, position_type const& p1) const = 0; + + virtual void save(const std::string& filename) const + { + throw ecell4::NotSupported( + ""save(const std::string) is not supported by this space class""); + } + + virtual void remove_particle(particle_id_type const& id) = 0; + + virtual length_type distance( + position_type const& lhs, position_type const& rhs) const = 0; + + virtual position_type apply_boundary(position_type const& v) const = 0; + + virtual position_type apply_reflection(const position_type& pos, const position_type& disp) + { + return pos + disp; + } + + virtual position_type apply_structure( + position_type const& pos, position_type const& disp) const = 0; +}; + +} // egfrd +} // ecell4 +#endif /* PARTICLE_CONTAINER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/generator.hpp",".hpp","6750","235","#ifndef ECELL4_EGFRD_GENERATOR_HPP +#define ECELL4_EGFRD_GENERATOR_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include ""utils/range.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +template +bool valid(Tgen_ const& t) +{ + return true; +} + +template +std::size_t count(Tgen_ const& t) +{ + throw std::runtime_error(""generation is not limited""); +} + +template +struct abstract_generator +{ + typedef Tretval_ result_type; + + virtual ~abstract_generator() {} + + virtual Tretval_ operator()() = 0; +}; + + +template +struct abstract_limited_generator: public abstract_generator +{ + virtual ~abstract_limited_generator() {} + + virtual std::size_t count() const + { + throw std::runtime_error(""indetermined""); + } + + virtual bool valid() const = 0; + + virtual Tretval_ operator()() = 0; +}; + + +template +bool valid(abstract_limited_generator const& gen) +{ + return gen.valid(); +} + +template +std::size_t count(abstract_limited_generator const& gen) +{ + return gen.count(); +} + +template::type, + typename Tresult_ = typename boost::iterator_reference::type, + bool Bra_ = + std::is_convertible< + typename boost::iterator_category_to_traversal< + typename std::iterator_traits::iterator_category + >::type, + boost::random_access_traversal_tag>::value> +class range_generator: public abstract_limited_generator +{ + template + friend bool valid(range_generator const& gen); + template + friend std::size_t count(range_generator const& gen); + +public: + typedef Titer_ range_iterator; + typedef Tresult_ result_type; + +public: + template + range_generator(Tanother_range_ const& range) + : i_(boost::begin(range)), end_(boost::end(range)), + count_(ecell4::egfrd::size(range)) {} + + template + range_generator(Tanother_range_& range) + : i_(boost::begin(range)), end_(boost::end(range)), + count_(ecell4::egfrd::size(range)) {} + + range_generator(range_iterator const& begin, range_iterator const& end) + : i_(begin), end_(end), count_(ecell4::egfrd::size(std::make_pair(begin, end))) {} + + virtual ~range_generator() {} + + virtual result_type operator()() + { + --count_; + return *i_++; + } + + virtual std::size_t count() const + { + return count_; + } + + virtual bool valid() const + { + return i_ != end_; + } + +private: + range_iterator i_, end_; + std::size_t count_; +}; + +template +class range_generator + : public abstract_limited_generator +{ + template + friend bool valid(range_generator const& gen); + template + friend std::size_t count(range_generator const& gen); + +public: + typedef Titer_ range_iterator; + typedef Tresult_ result_type; + +public: + template + range_generator(Tanother_range_ const& range) + : i_(boost::begin(range)), end_(boost::end(range)) {} + + template + range_generator(Tanother_range_& range) + : i_(boost::begin(range)), end_(boost::end(range)) {} + + range_generator(range_iterator const& begin, range_iterator const& end) + : i_(begin), end_(end) {} + + template + range_generator(Tanother_range_ const& range, std::size_t count) + : i_(boost::begin(range)), end_(boost::end(range)), + count_(count) {} + + template + range_generator(Tanother_range_& range, std::size_t count) + : i_(boost::begin(range)), end_(boost::end(range)), + count_(count) {} + + range_generator(range_iterator const& begin, range_iterator const& end, + std::size_t count) + : i_(begin), end_(end), count_(count) {} + + virtual ~range_generator() {} + + virtual result_type operator()() + { + if (count_.is_initialized()) + { + --boost::get(count_); + } + return *i_++; + } + + virtual std::size_t count() const + { + if (count_.is_initialized()) + { + return boost::get(count_); + } + throw std::runtime_error(""count not given through the constructor""); + } + + virtual bool valid() const + { + return i_ != end_; + } + +private: + range_iterator i_, end_; + boost::optional count_; +}; + +template +inline abstract_limited_generator::type>::type >* +make_range_generator(T_& range) +{ + return new range_generator::type, typename boost::iterator_reference::type>::type>(range); +} + +template +inline abstract_limited_generator* +make_range_generator(T_& range) +{ + return new range_generator::type, Tresult_>(range); +} + +template +inline abstract_limited_generator::type>::type >* +make_range_generator(T_ const& range) +{ + return new range_generator::type, typename boost::iterator_reference::type>::type>(range); +} + +template +inline abstract_limited_generator* +make_range_generator(T_ const& range) +{ + return new range_generator::type, Tresult_>(range); +} + +} // egfrd +} // ecell4 +#endif /* GENERATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/geometry.hpp",".hpp","6765","227","#ifndef ECELL4_EGFRD_GEOMETRY_HPP +#define ECELL4_EGFRD_GEOMETRY_HPP + +#include +#include ""linear_algebra.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +template< typename T1_, typename T2_ > +inline typename element_type_of< T1_ >::type distance( + T1_ const& p1, T2_ const p2, + typename std::enable_if< + boost::mpl::and_< + is_vector3, + is_vector3 >::value >::type* = 0) +{ + return std::sqrt( + pow_2( p1[0] - p2[0] ) + + pow_2( p1[1] - p2[1] ) + + pow_2( p1[2] - p2[2] ) ); +} + +template +inline typename element_type_of::type distance(T_ const& p1, T_ const& p2) +{ + return distance(p1, p2, (void*)0); +} + +template +inline T_ normalize(T_ const& p) +{ + return divide(p, length(p)); +} + +template +inline T_ normalize(T_ const& p, + typename element_type_of< T_ >::type const& r) +{ + return multiply(p, r / length(p)); +} + + +/** + * Transpose the position pos1 so that it can be used with another + * position pos2. + * + * pos1 is transposed into one of mirror images of the cyclic boundary + * condition so that the distance between pos1 and pos2 is smallest. + * + * Both of given pos1 and pos2 must be within the cyclic boundary. However, + * note that the returned transposed pos1 may not be within the cyclic boundary. + */ +template +inline T_ periodic_transpose(T_ const& p0, T_ const& p1, T_ const& world_size, typename std::enable_if::value>::type*) +{ + const T_ diff(p1 - p0), half(world_size / 2); + if (diff > half) + { + return p0 + world_size; + } + else if (diff < -half) + { + return p0 - world_size; + } + else + { + return p0; + } +} + +template +inline T_ periodic_transpose(T_ const& p0, T_ const& p1, typename element_type_of::type const& world_size, typename std::enable_if::value>::type*) +{ + T_ retval; + retval[0] = periodic_transpose(p0[0], p1[0], world_size, (void*)0); + retval[1] = periodic_transpose(p0[1], p1[1], world_size, (void*)0); + retval[2] = periodic_transpose(p0[2], p1[2], world_size, (void*)0); + return retval; +} + +template +inline T_ periodic_transpose(T_ const& p0, T_ const& p1, T_ const& edge_lengths, typename std::enable_if::value>::type*) +{ + T_ retval; + retval[0] = periodic_transpose(p0[0], p1[0], edge_lengths[0], (void*)0); + retval[1] = periodic_transpose(p0[1], p1[1], edge_lengths[1], (void*)0); + retval[2] = periodic_transpose(p0[2], p1[2], edge_lengths[2], (void*)0); + return retval; +} + +template +inline T1_ periodic_transpose(T1_ const& p0, T1_ const& p1, T2_ const& world_size) +{ + return periodic_transpose(p0, p1, world_size, (void*)0); +} + +template +inline T_ apply_boundary(T_ const& p1, T_ const& world_size, typename std::enable_if::value>::type*) +{ + return modulo(p1, world_size); +} + +template +inline T_ apply_boundary(T_ const& p1, + typename element_type_of::type const& world_size, + typename std::enable_if::value>::type*) +{ + return modulo(p1, world_size); +} + +template +inline T1_ apply_boundary(T1_ const& p1, T2_ const& edge_lengths, typename std::enable_if, is_vector3 >::value>::type*) +{ + return modulo(p1, edge_lengths); +} + +template +inline T1_ apply_boundary(T1_ const& p1, T2_ const& world_size) +{ + return apply_boundary(p1, world_size, (void*)0); +} + +template +inline typename element_type_of::type distance_cyclic( + T1_ const& p1, T2_ const& p2, + typename element_type_of::type const& world_size, + typename std::enable_if< + boost::mpl::and_< + is_vector3, + is_vector3 >::value>::type* = 0) +{ + return distance(p1, periodic_transpose(p2, p1, world_size)); +} + +template +inline typename element_type_of::type distance_cyclic( + T1_ const& p1, T2_ const& p2, T3_ const& edge_lengths, + typename std::enable_if< + boost::mpl::and_< + is_vector3, + is_vector3, + is_vector3 >::value>::type* = 0) +{ + return distance(p1, periodic_transpose(p2, p1, edge_lengths)); +} + +template +inline typename element_type_of::type +distance_cyclic(T_ const& p1, T_ const& p2, + typename element_type_of::type const& world_size) +{ + return distance_cyclic(p1, p2, world_size, (void*)0); +} + +template +inline T spherical_to_cartesian(T const& s) +{ + typename element_type_of::type const sintheta(std::sin(s[1])); + T retval; + retval[0] = s[0] * std::cos(s[2]) * sintheta; + retval[1] = s[0] * std::sin(s[2]) * sintheta; + retval[2] = s[0] * std::cos(s[1]); + return retval; +} + +template +inline T1 rotate_vector(T1 const& v, T2 const& axis, double angle) +{ + double const c(std::cos(angle)), s(std::sin(angle)), cc(1. - c); + double const mat[3][3] = { + { + c + cc * axis[0] * axis[0], + cc * axis[0] * axis[1] - axis[2] * s, + cc * axis[0] * axis[2] + axis[1] * s + }, + { + cc * axis[0] * axis[1] + axis[2] * s, + c + cc * axis[1] * axis[1], + cc * axis[1] * axis[2] - axis[0] * s + }, + { + cc * axis[0] * axis[2] - axis[1] * s, + cc * axis[1] * axis[2] + axis[0] * s, + c + cc * axis[2] * axis[2] + } + }; + + return multiply(mat, v); +} + +// reflect +template +coordT reflect_plane(const coordT& begin, const coordT& end, + const coordT& normal, const coordT& plane) +{ + typedef typename element_type_of::type valueT; +// assert(std::abs(length(normal) - 1.0) < 1e-12); + const valueT norm_b = dot_product((begin - plane), normal); + const valueT norm_e = dot_product((end - plane), normal); + if(norm_b == 0.0) + { + throw std::invalid_argument(""reflection: begin is on the plane""); + } + else if(norm_b * norm_e > 0.0 && std::abs(norm_e) < 1e-10) + { + return (begin * 1e-10) + (end * (1.0 - 1e-10)); + } + else if(norm_b * norm_e < 0.0 && std::abs(norm_e) < 1e-10) + { + return begin * 1e-10 + (end - (normal * (norm_e * 2.0))) * (1. - 1e-10); + } + else if(norm_b * norm_e > 0.0) + { + return end; + } + else + { + return end - (normal * (norm_e * 2.0)); + } +} +} // egfrd +} // ecell4 +#endif /* GEOMETRY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ParticleTraits.hpp",".hpp","3867","159","#ifndef ECELL4_EGFRD_PARTICLE_TRAITS_HPP +#define ECELL4_EGFRD_PARTICLE_TRAITS_HPP + +#include +#include +#include +// #include ""Sphere.hpp"" +// #include ""Shape.hpp"" +//XXX: Shape.hpp +#include ""Real3Type.hpp"" +#include ""geometry.hpp"" +//XXX + +namespace ecell4 +{ +namespace egfrd +{ +inline ecell4::Particle offset( + ecell4::Particle const& shape, ecell4::Particle::position_type off) +{ + ecell4::Particle retval(shape); + retval.position() += off; + return retval; +} + +// inline +// ecell4::Sphere shape(ecell4::Particle &p) +// { +// return ecell4::Sphere(p.position(), p.radius()); +// } + +inline +ecell4::Sphere shape(const ecell4::Particle &p) +{ + return ecell4::Sphere(p.position(), p.radius()); +} + +// inline ecell4::Sphere offset( +// const ecell4::Sphere& shape, ecell4::Sphere::position_type off) +// { +// ecell4::Sphere retval(shape); +// retval.position() += off; +// return retval; +// } + +inline ecell4::Sphere::length_type +distance(const ecell4::Sphere& obj, const ecell4::Sphere::position_type& pos) +{ + return ecell4::egfrd::distance(pos, obj.position()) - obj.radius(); +} + +template +inline ecell4::Sphere::length_type +distance_cyclic( + const ecell4::Sphere& p1, T_ const& p2, + const ecell4::Sphere::position_type& edge_lengths) +{ + return distance(p1, periodic_transpose(p2, p1.position(), edge_lengths)); +} + +inline ecell4::Sphere::length_type const& shape_size(ecell4::Sphere const& shape) +{ + return shape.size(); +} + +inline ecell4::Sphere::length_type& shape_size(ecell4::Sphere &shape) +{ + return shape.size(); +} + +inline ecell4::Sphere::position_type const& shape_position(ecell4::Sphere const& shape) +{ + return shape.position(); +} + +inline ecell4::Sphere::position_type& shape_position(ecell4::Sphere &shape) +{ + return shape.position(); +} + +template<> +struct shape_position_type { + typedef ecell4::Sphere::position_type type; +}; + +// inline ecell4::Cylinder offset( +// const ecell4::Cylinder& shape, ecell4::Cylinder::position_type off) +// { +// ecell4::Cylinder retval(shape); +// retval.position() += off; +// return retval; +// } + +inline ecell4::Cylinder::length_type +distance(const ecell4::Cylinder& obj, const ecell4::Cylinder::position_type& pos) +{ + return ecell4::egfrd::distance(pos, obj.position()) - obj.radius(); +} + +template +inline ecell4::Cylinder::length_type +distance_cyclic( + const ecell4::Cylinder& p1, T_ const& p2, + const ecell4::Cylinder::position_type& edge_lengths) +{ + return distance(p1, periodic_transpose(p2, p1.position(), edge_lengths)); +} + +inline ecell4::Cylinder::length_type const& shape_size(ecell4::Cylinder const& shape) +{ + return shape.size(); +} + +inline ecell4::Cylinder::length_type& shape_size(ecell4::Cylinder &shape) +{ + return shape.size(); +} + +inline ecell4::Cylinder::position_type const& shape_position(ecell4::Cylinder const& shape) +{ + return shape.position(); +} + +inline ecell4::Cylinder::position_type& shape_position(ecell4::Cylinder &shape) +{ + return shape.position(); +} + +template<> +struct shape_position_type { + typedef ecell4::Cylinder::position_type type; +}; + +} // egfrd +} // ecell4 + +namespace ecell4 +{ + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& strm, const ecell4::Sphere& v) +{ + strm << ""{"" << v.position() << "", "" << v.radius() << ""}""; + return strm; +} + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& strm, const ecell4::Cylinder& v) +{ + strm << ""{"" << v.position() << "", "" << v.radius() + << "", "" << v.axis() << "", "" << v.half_height() << ""}""; + return strm; +} + +} // ecell4 +#endif +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/AnalyticalPair.hpp",".hpp","6296","206","#ifndef ECELL4_EGFRD_ANALYTICAL_PAIR_HPP +#define ECELL4_EGFRD_ANALYTICAL_PAIR_HPP + +#include +#include +#include ""Pair.hpp"" +#include ""AnalyticalSingle.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +template +class AnalyticalPair: public Pair +{ +public: + typedef Pair base_type; + typedef Ttraits_ traits_type; + typedef typename traits_type::world_type::length_type length_type; + typedef typename traits_type::world_type::position_type position_type; + typedef typename traits_type::world_type::particle_id_pair particle_id_pair; + typedef typename traits_type::world_type::traits_type::D_type D_type; + typedef typename traits_type::domain_id_type identifier_type; + typedef typename traits_type::shell_id_type shell_id_type; + typedef typename traits_type::network_rules_type network_rules_type; + typedef typename network_rules_type::reaction_rule_type reaction_rule_type; + typedef typename network_rules_type::reaction_rule_vector reaction_rule_vector; + typedef Tshell_ shell_type; + typedef std::pair shell_id_pair; + +public: + virtual ~AnalyticalPair() {} + + AnalyticalPair(identifier_type const& id, + particle_id_pair const& p0, particle_id_pair const& p1, + shell_id_pair const& shell, + position_type const& iv, + reaction_rule_vector const& reactions) + : base_type(id, p0, p1), shell_(shell), iv_(iv), reactions_(reactions) + { + // determine a_r and a_R + { + D_type D0(base_type::particles_[0].second.D()); + D_type D1(base_type::particles_[1].second.D()); + length_type R0(base_type::particles_[0].second.radius()); + length_type R1(base_type::particles_[1].second.radius()); + const length_type sigma(R0 + R1); + const length_type D_tot(D0 + D1); + const length_type D_geom(std::sqrt(D0 * D1)); + const length_type shell_size(shell.second.shape().radius() / traits_type::SAFETY); + const length_type r0(this->r0()); + BOOST_ASSERT(r0 >= sigma); + if (((D_geom - D0) * r0) / D_tot + shell_size + + std::sqrt(D0 / D1) * (R1 - shell_size) - R0 < 0) + { + std::swap(D0, D1); + std::swap(R0, R1); + } + a_R_ = D_geom * (D0 * (shell_size - R1) + + D1 * (shell_size - r0 - R1)) / + (D1 * D1 + D1 * D0 + D_geom * D_tot); + a_r_ = (D_geom * r0 + D_tot * (shell_size - R1)) / (D1 + D_geom); + BOOST_ASSERT(a_r_ > 0); + BOOST_ASSERT(a_r_ > r0); + BOOST_ASSERT(a_R_ > 0 || (a_R_ == 0. && (D1 == 0. || D0 == 0.))); + BOOST_ASSERT(a_R_ + a_r_ * D1 / D_tot + R1 >= + a_R_ + a_r_ * D0 / D_tot + R0); + BOOST_ASSERT(std::abs(a_R_ + a_r_ * D1 / D_tot + R1 - shell_size) < + 1e-12 * shell_size); + } + } + + shell_id_pair const& shell() const + { + return shell_; + } + + shell_id_pair& shell() + { + return shell_; + } + + position_type const& iv() const + { + return iv_; + } + + length_type r0() const + { + return length(iv_); + } + + length_type const& a_R() const + { + return a_R_; + } + + length_type const& a_r() const + { + return a_r_; + } + + length_type sigma() const + { + return base_type::particles_[0].second.radius() + + base_type::particles_[1].second.radius(); + } + + D_type D_tot() const + { + return base_type::particles_[0].second.D() + + base_type::particles_[1].second.D(); + } + + D_type D_geom() const + { + return std::sqrt( + base_type::particles_[0].second.D() * + base_type::particles_[1].second.D()); + } + + D_type D_R() const + { + return base_type::particles_[0].second.D() * + base_type::particles_[1].second.D() / D_tot(); + } + + virtual position_type const& position() const + { + return shape_position(shell_.second.shape()); + } + + virtual position_type& position() + { + return shape_position(shell_.second.shape()); + } + + virtual length_type const& size() const + { + return shape_size(shell_.second.shape()); + } + + virtual length_type& size() + { + return shape_size(shell_.second.shape()); + } + + virtual char const* type_name() const + { + return retrieve_domain_type_name(*this); + } + + reaction_rule_vector const& reactions() const + { + return reactions_; + } + + virtual typename Domain::size_type num_shells() const + { + return 1; + } + + virtual typename Domain::size_type multiplicity() const + { + return 2; + } + + virtual void accept(ImmutativeDomainVisitor const& visitor) const + { + visitor(*this); + } + + virtual void accept(MutativeDomainVisitor const& visitor) + { + visitor(*this); + } + + virtual std::string as_string() const + { + return (boost::format( + ""%s(id=%s, event=%s, last_time=%.16g, dt=%.16g, particles=[(%s:%s), (%s:%s)], iv=%s, shell=(%s:%s))"") % + type_name() % + boost::lexical_cast(base_type::id_) % + boost::lexical_cast(base_type::event_.first) % + base_type::last_time_ % base_type::dt_ % + boost::lexical_cast(base_type::particles()[0].first) % + boost::lexical_cast(base_type::particles()[0].second) % + boost::lexical_cast(base_type::particles()[1].first) % + boost::lexical_cast(base_type::particles()[1].second) % + boost::lexical_cast(iv_) % + boost::lexical_cast(shell_.first) % + boost::lexical_cast(shell_.second)).str(); + } +protected: + shell_id_pair shell_; + position_type const iv_; + reaction_rule_vector const& reactions_; + mutable length_type a_R_; + mutable length_type a_r_; +}; + +} // egfrd +} // ecell4 +#endif /* ANALYTICAL_PAIR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/sorted_list.hpp",".hpp","5706","204","#ifndef ECELL4_EGFRD_SORTED_LIST +#define ECELL4_EGFRD_SORTED_LIST + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include ""utils/fun_composition.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ +template::type>, typename Tholder_ = Tcntnr_> +class sorted_list +{ +public: + typedef Tcntnr_ container_type; + typedef Tholder_ holder_type; + typedef typename boost::range_value::type value_type; + typedef typename boost::range_size::type size_type; + typedef typename boost::range_difference::type difference_type; + typedef typename boost::range_iterator::type iterator; + typedef typename boost::range_const_iterator::type const_iterator; + typedef typename boost::range_reverse_iterator::type reverse_iterator; + typedef typename boost::range_const_reverse_iterator::type const_reverse_iterator; + + typedef value_type* pointer; + typedef value_type const* const_pointer; + typedef value_type& reference; + typedef value_type const& const_reference; + + size_type size() const + { + return boost::size(static_cast(cntnr_)); + } + + iterator begin() + { + return boost::begin(static_cast(cntnr_)); + } + + const_iterator begin() const + { + return boost::begin(static_cast(cntnr_)); + } + + iterator end() + { + return boost::end(static_cast(cntnr_)); + } + + const_iterator end() const + { + return boost::end(static_cast(cntnr_)); + } + + reverse_iterator rbegin() + { + return boost::rbegin(static_cast(cntnr_)); + } + + const_reverse_iterator rbegin() const + { + return boost::rbegin(static_cast(cntnr_)); + } + + reverse_iterator rend() + { + return boost::rend(static_cast(cntnr_)); + } + + const_reverse_iterator rend() const + { + return boost::end(static_cast(cntnr_)); + } + + void push(value_type const& v) + { + iterator i(std::upper_bound(begin(), end(), v, + static_cast(ord_))); + static_cast(cntnr_).insert(i, v); + } + + bool push_no_duplicate(value_type const& v) + { + iterator i(std::upper_bound(begin(), end(), v, + static_cast(ord_))); + if (i != begin()) + { + if (*--i == v) + return false; + ++i; + } + static_cast(cntnr_).insert(i, v); + return true; + } + + bool update(value_type const& v) + { + iterator i(std::upper_bound(begin(), end(), v, + static_cast(ord_))); + if (i != begin()) + { + if (*--i == v) + { + value_type _v(v); + std::swap(*i, _v); + return false; + } + ++i; + } + static_cast(cntnr_).insert(i, v); + return true; + } + + + void erase(iterator const& i) + { + static_cast(cntnr_).erase(i); + } + + iterator find(value_type const& v) + { + iterator i(std::lower_bound(begin(), end(), v, + static_cast(ord_))); + return i != end() && *i == v ? i: end(); + } + + const_iterator find(value_type const& v) const + { + const_iterator i(std::lower_bound(begin(), end(), v, + static_cast(ord_))); + return i != end() && *i == v ? i: end(); + } + + reverse_iterator rfind(value_type const& v) + { + reverse_iterator i(std::upper_bound(rbegin(), rend(), v, + fun_composition(std::logical_not(), ord_))); + return i != rend() && *i == v ? i: rend(); + } + + const_reverse_iterator rfind(value_type const& v) const + { + const_reverse_iterator i(std::upper_bound(rbegin(), rend(), v, + fun_composition(std::logical_not(), ord_))); + return i != rend() && *i == v ? i: rend(); + } + + size_type erase(value_type const& v) + { + iterator e(end()); + std::pair i(std::equal_range(begin(), e, v, + static_cast(ord_))); + const size_type retval(i.second - i.first); + static_cast(cntnr_).erase(i.first, i.second); + return retval; + } + + void clear() + { + static_cast(cntnr_).clear(); + } + + holder_type& container() + { + return cntnr_; + } + + holder_type const& container() const + { + return cntnr_; + } + + sorted_list(const TweakOrdering_& ord, const holder_type& holder) + : ord_(ord), cntnr_(holder) {} + + explicit sorted_list(const holder_type& holder) + : ord_(), cntnr_(holder) {} + + explicit sorted_list(const TweakOrdering_& ord): ord_(ord) {} + + sorted_list(): ord_() {} + +private: + TweakOrdering_ ord_; + holder_type cntnr_; +}; + +} // egfrd +} // ecell4 +#endif /* EGFRD_SORTED_LIST */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/VolumeClearer.hpp",".hpp","656","28","#ifndef ECELL4_EGFRD_VOLUME_CLEARER_HPP +#define ECELL4_EGFRD_VOLUME_CLEARER_HPP +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +class VolumeClearer +{ +public: + typedef ecell4::Sphere particle_shape_type; + typedef ecell4::ParticleID particle_id_type; + +public: + virtual ~VolumeClearer() {} + + virtual bool operator()(particle_shape_type const& shape, particle_id_type const& ignore) = 0; + + virtual bool operator()(particle_shape_type const& shape, particle_id_type const& ignore0, particle_id_type const& ignore1) = 0; +}; + +} // egfrd +} // ecell4 +#endif /* VOLUME_CLEARER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/ReactionRecord.hpp",".hpp","3957","143","#ifndef ECELL4_EGFRD_REACTION_RECORD_HPP +#define ECELL4_EGFRD_REACTION_RECORD_HPP + +#include +#include ""utils/memberwise_compare.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ +template +class ReactionRecord +{ +public: + typedef Tpid_ particle_id_pair; + typedef Trid_ reaction_rule_id_type; + typedef std::vector container_type; + typedef container_type products_type; + typedef container_type reactants_type; + +public: + ReactionRecord() + : reaction_rule_id_(), reactants_(), products_() {} + + template + ReactionRecord(reaction_rule_id_type const& rid, + Tset const& products) + : reaction_rule_id_(rid), reactants_(), + products_(boost::begin(products), boost::end(products)) {} + + template + ReactionRecord(reaction_rule_id_type const& rid, + Tset const& products, + particle_id_pair const& p1) + : reaction_rule_id_(rid), reactants_(1, p1), + products_(boost::begin(products), boost::end(products)) {} + + template + ReactionRecord(reaction_rule_id_type const& rid, + Tset const& products, + particle_id_pair const& p1, particle_id_pair const& p2) + : reaction_rule_id_(rid), reactants_(), + products_(boost::begin(products), boost::end(products)) + { + reactants_.push_back(p1); + reactants_.push_back(p2); + } + + // HEADS UP: move constructor! + ReactionRecord(ReactionRecord const& that) + { + swap(const_cast(that)); + } + + reaction_rule_id_type const& reaction_rule_id() const + { + return reaction_rule_id_; + } + + reactants_type const& reactants() const + { + return reactants_; + } + + products_type const& products() const + { + return products_; + } + + operator bool() const + { + return reactants_.size() != 0; + } + + bool operator==(ReactionRecord const& rhs) const + { + return reaction_rule_id_ == rhs.reaction_rule_id() && + memberwise_compare(reactants_, rhs.reactants_) == 0 && + memberwise_compare(products_, rhs.products_) == 0; + } + + bool operator!=(ReactionRecord const& rhs) const + { + return !operator==(rhs); + } + + void swap(ReactionRecord& that) + { + std::swap(reaction_rule_id_, that.reaction_rule_id_); + reactants_.swap(that.reactants_); + products_.swap(that.products_); + } + +protected: + reaction_rule_id_type reaction_rule_id_; + reactants_type reactants_; + products_type products_; +}; + +template +inline std::basic_ostream& +operator<<(std::basic_ostream& out, + ReactionRecord const& r) +{ + bool first; + out << ""ReactionRecord(reaction_rule_id="" << r.reaction_rule_id() << "", ""; + out << ""reactants={""; + typedef typename ReactionRecord::reactants_type reactants_type; + typedef typename ReactionRecord::products_type products_type; + reactants_type const& reactants(r.reactants()); + for (typename boost::range_const_iterator::type + i(boost::begin(reactants)), e(boost::end(reactants)); + i != e; ++i) + { + if (!first) + { + out << "", ""; + } + out << (*i).first; + first = false; + } + out << ""}, products={""; + first = true; + products_type const& products(r.products()); + for (typename boost::range_const_iterator::type + i(boost::begin(products)), e(boost::end(products)); + i != e; ++i) + { + if (!first) + { + out << "", ""; + } + out << (*i).first; + first = false; + } + out << ""})""; + return out; +} + +} // egfrd +} // ecell4 +#endif /* REACTION_RECORD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/AnalyticalSingle.hpp",".hpp","3270","116","#ifndef ECELL4_EGFRD_ANALYTICAL_SINGLE_HPP +#define ECELL4_EGFRD_ANALYTICAL_SINGLE_HPP + +#include ""Single.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ +template +class AnalyticalSingle: public Single +{ +public: + typedef Single base_type; + typedef Ttraits_ traits_type; + typedef typename traits_type::world_type::length_type length_type; + typedef typename traits_type::world_type::position_type position_type; + typedef typename traits_type::world_type::particle_id_pair particle_id_pair; + typedef typename traits_type::domain_id_type identifier_type; + typedef typename traits_type::shell_id_type shell_id_type; + typedef typename traits_type::network_rules_type network_rules_type; + typedef Tshell_ shell_type; + typedef std::pair shell_id_pair; + typedef typename network_rules_type::reaction_rule_vector reaction_rule_vector; + typedef typename traits_type::rate_type rate_type; + +public: + virtual ~AnalyticalSingle() {} + + AnalyticalSingle(identifier_type const& id, + particle_id_pair const& particle, + shell_id_pair const& shell) + : base_type(id, particle), shell_(shell) {} + + shell_id_pair const& shell() const + { + return shell_; + } + + shell_id_pair& shell() + { + return shell_; + } + + length_type mobility_radius() const + { + return shape_size(shell_.second.shape()) - base_type::particle().second.radius(); + } + + virtual char const* type_name() const + { + return retrieve_domain_type_name(*this); + } + + virtual position_type const& position() const + { + return shape_position(shell_.second.shape()); + } + + virtual position_type& position() + { + return shape_position(shell_.second.shape()); + } + + virtual length_type const& size() const + { + return shape_size(shell_.second.shape()); + } + + virtual length_type& size() + { + return shape_size(shell_.second.shape()); + } + + virtual typename Domain::size_type num_shells() const + { + return 1; + } + + virtual typename Domain::size_type multiplicity() const + { + return 1; + } + + virtual void accept(ImmutativeDomainVisitor const& visitor) const + { + visitor(*this); + } + + virtual void accept(MutativeDomainVisitor const& visitor) + { + visitor(*this); + } + + virtual std::string as_string() const + { + return (boost::format( + ""%s(id=%s, event=%s, last_time=%.16g, dt=%.16g, particle=(%s:%s), shell=(%d:%s))"") % + type_name() % + boost::lexical_cast(base_type::id_) % + boost::lexical_cast(base_type::event_.first) % + base_type::last_time_ % base_type::dt_ % + boost::lexical_cast(base_type::particle().first) % + boost::lexical_cast(base_type::particle().second) % + boost::lexical_cast(shell_.first) % + boost::lexical_cast(shell_.second)).str(); + } + +protected: + shell_id_pair shell_; +}; + +} // egfrd +} // ecell4 +#endif /* ANALYTICAL_SINGLE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/DomainID.hpp",".hpp","964","46","#ifndef ECELL4_EGFRD_DOMAIN_ID_HPP +#define ECELL4_EGFRD_DOMAIN_ID_HPP + +#include +#include +// #include ""Identifier.hpp"" +#include + +namespace ecell4 +{ +namespace egfrd +{ + +struct DomainID: public ecell4::Identifier +{ + typedef ecell4::Identifier base_type; + + DomainID(value_type const& value = value_type(0, 0)) + : base_type(value) {} +}; + +template +inline std::basic_ostream& operator<<(std::basic_ostream& strm, + const DomainID& v) +{ + strm << ""DID("" << v().first << "":"" << v().second << "")""; + return strm; +} + +} // egfrd +} // ecell4 + +namespace std { + +template<> +struct hash +{ + std::size_t operator()(ecell4::egfrd::DomainID const& val) const + { + return static_cast(val().first ^ val().second); + } +}; + +} // std +#endif /* DOMAIN_ID_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/Multi.hpp",".hpp","16453","520","#ifndef ECELL4_EGFRD_MULTI_HPP +#define ECELL4_EGFRD_MULTI_HPP + +#include +#include + +#include ""exceptions.hpp"" +#include ""Domain.hpp"" +#include ""ParticleContainer.hpp"" +// #include ""Sphere.hpp"" +// #include ""BDSimulator.hpp"" +#include ""BDPropagator.hpp"" +#include ""Logger.hpp"" +#include ""VolumeClearer.hpp"" +#include ""utils/array_helper.hpp"" +#include ""utils/collection_contains.hpp"" +#include ""utils/range.hpp"" +#include ""utils/stringizer.hpp"" + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +class MultiParticleContainer + : public Ttraits_::world_type::particle_container_type +{ +public: + + typedef typename Ttraits_::world_type::particle_container_type base_type; + typedef typename Ttraits_::world_type world_type; + typedef typename world_type::traits_type traits_type; + // typedef ParticleContainerUtils utils; + + typedef typename traits_type::particle_type particle_type; + typedef typename traits_type::particle_shape_type particle_shape_type; + typedef typename traits_type::molecule_info_type molecule_info_type; + typedef typename traits_type::species_id_type species_id_type; + typedef typename traits_type::position_type position_type; + typedef typename traits_type::particle_id_type particle_id_type; + typedef typename traits_type::length_type length_type; + typedef typename traits_type::size_type size_type; + typedef typename traits_type::structure_id_type structure_id_type; + typedef typename traits_type::structure_type structure_type; + typedef typename traits_type::particle_id_pair particle_id_pair; + typedef typename traits_type::particle_id_pair_generator + particle_id_pair_generator; + typedef typename traits_type::particle_id_pair_and_distance + particle_id_pair_and_distance; + typedef typename traits_type::particle_id_pair_and_distance_list + particle_id_pair_and_distance_list; + + //XXX: typedef std::map particle_map; + typedef std::unordered_map particle_map; + typedef sized_iterator_range particle_id_pair_range; + + typedef typename world_type::particle_container_type::time_type time_type; + + virtual ~MultiParticleContainer() {} + + virtual ecell4::Integer num_particles() const + { + return particles_.size(); + } + + // virtual size_type num_particles() const + // { + // return particles_.size(); + // } + + virtual const position_type& edge_lengths() const + { + return world_.edge_lengths(); + } + + // virtual molecule_info_type const& find_molecule_info(species_id_type const& id) const + // { + // return world_.find_molecule_info(id); + // } + + // virtual molecule_info_type const& get_molecule_info(species_id_type const& id) + // { + // return world_.get_molecule_info(id); + // } + + virtual molecule_info_type get_molecule_info(species_id_type const& id) const + { + return world_.get_molecule_info(id); + } + + virtual std::shared_ptr get_structure(structure_id_type const& id) const + { + return world_.get_structure(id); + } + + virtual std::pair new_particle(species_id_type const& sid, + position_type const& pos) + { + std::pair const retval(world_.new_particle(sid, pos)); + particles_.insert(retval.first); + return retval; + } + + virtual bool update_particle(const particle_id_type& pid, const particle_type& p) + { + world_.update_particle(pid, p); + typename particle_map::iterator const i(particles_.find(pid)); + if (i != particles_.end()) + { + (*i).second = p; + return false; + } + else + { + particles_.insert(i, std::make_pair(pid, p)); + return true; + } + } + + virtual void remove_particle(particle_id_type const& id) + { + world_.remove_particle(id); + particles_.erase(id); + } + + virtual particle_id_pair get_particle(particle_id_type const& id) const + { + typename particle_map::const_iterator i(particles_.find(id)); + if (particles_.end() == i) + { + throw ::ecell4::NotFound(std::string(""No such particle: id="") + + boost::lexical_cast(id)); + } + return *i; + } + + virtual bool has_particle(particle_id_type const& id) const + { + return particles_.end() != particles_.find(id); + } + + virtual particle_id_pair_and_distance_list check_overlap(particle_shape_type const& s) const + { + return check_overlap(s, array_gen()); + } + + virtual particle_id_pair_and_distance_list check_overlap(particle_shape_type const& s, particle_id_type const& ignore) const + { + return check_overlap(s, array_gen(ignore)); + } + + virtual particle_id_pair_and_distance_list check_overlap(particle_shape_type const& s, particle_id_type const& ignore1, particle_id_type const& ignore2) const + { + return check_overlap(s, array_gen(ignore1, ignore2)); + } + + template + particle_id_pair_and_distance_list check_overlap(Tsph_ const& s, Tset_ const& ignore) const + { + particle_id_pair_and_distance_list retval; + for (typename particle_map::const_iterator i(particles_.begin()), + e(particles_.end()); + i != e; ++i) + { + length_type const dist(world_.distance(shape((*i).second), s.position())); + if (dist < s.radius() && !collection_contains(ignore, (*i).first)) + { + retval.push_back(std::make_pair(*i, dist)); + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator()); + return retval; + } + + virtual length_type distance(position_type const& lhs, + position_type const& rhs) const + { + return world_.distance(lhs, rhs); + } + + virtual position_type apply_boundary(position_type const& v) const + { + return world_.apply_boundary(v); + } + + // virtual length_type apply_boundary(length_type const& v) const + // { + // return world_.apply_boundary(v); + // } + + virtual position_type apply_structure( + position_type const& p, position_type const& d) const + { + return world_.apply_structure(p, d); + } + + virtual position_type periodic_transpose(position_type const& p0, position_type const& p1) const + { + return world_.periodic_transpose(p0, p1); + } + + // virtual length_type periodic_transpose(length_type const& p0, length_type const& p1) const + // { + // return world_.periodic_transpose(p0, p1); + // } + + particle_id_pair_range get_particles_range() const + { + return particle_id_pair_range(particles_.begin(), particles_.end(), + particles_.size()); + } + + MultiParticleContainer(world_type& world): world_(world) {} + + /** ecell4::Space + */ + // virtual const time_type& t() const + virtual const time_type t() const + { + return world_.t(); + } + + virtual void set_t(const time_type& t) + { + world_.set_t(t); + } + +private: + world_type& world_; + particle_map particles_; +}; + +template +class Multi: public Domain +{ +public: + + typedef Tsim_ simulator_type; + typedef typename simulator_type::traits_type traits_type; + typedef Domain base_type; + typedef typename traits_type::world_type world_type; + + typedef typename world_type::particle_type particle_type; + typedef typename world_type::particle_shape_type particle_shape_type; + typedef typename world_type::molecule_info_type molecule_info_type; + typedef typename world_type::species_id_type species_id_type; + typedef typename world_type::position_type position_type; + typedef typename world_type::particle_id_type particle_id_type; + typedef typename world_type::length_type length_type; + typedef typename world_type::size_type size_type; + typedef typename world_type::structure_type structure_type; + typedef typename world_type::particle_id_pair particle_id_pair; + typedef typename world_type::particle_id_pair_and_distance + particle_id_pair_and_distance; + typedef typename world_type::particle_id_pair_and_distance_list + particle_id_pair_and_distance_list; + + typedef typename traits_type::shell_id_type shell_id_type; + typedef typename traits_type::domain_id_type identifier_type; + typedef typename traits_type::template shell_generator< + ecell4::Sphere>::type spherical_shell_type; + // typedef typename traits_type::template shell_generator< + // typename simulator_type::sphere_type>::type spherical_shell_type; + typedef std::pair spherical_shell_id_pair; + typedef typename traits_type::reaction_record_type reaction_record_type; + + //XXX: typedef std::map spherical_shell_map; + typedef std::unordered_map spherical_shell_map; + typedef sized_iterator_range spherical_shell_id_pair_range; + typedef MultiParticleContainer multi_particle_container_type; + + enum event_kind + { + NONE, + ESCAPE, + REACTION, + NUM_MULTI_EVENT_KINDS + }; + +private: + struct last_reaction_setter: ReactionRecorder + { + virtual ~last_reaction_setter() {} + + virtual void operator()(reaction_record_type const& rec) + { + outer_.last_reaction_.swap(const_cast(rec)); + } + + last_reaction_setter(Multi& outer): outer_(outer) {} + + Multi& outer_; + }; + + struct volume_clearer final: VolumeClearer + { + ~volume_clearer() override {} + + bool operator()(particle_shape_type const& shape, particle_id_type const& ignore) override + { + if (!outer_.within_shell(shape)) + { + outer_.last_event_ = ESCAPE; + return outer_.clear_volume(shape, ignore); + } + return true; + } + + bool operator()(particle_shape_type const& shape, particle_id_type const& ignore0, particle_id_type const& ignore1) override + { + if (!outer_.within_shell(shape)) + { + outer_.last_event_ = ESCAPE; + return outer_.clear_volume(shape, ignore0, ignore1); + } + return true; + } + + volume_clearer(Multi& outer): outer_(outer) {} + + Multi& outer_; + }; + + friend struct volume_clearer; + +public: + virtual ~Multi() {} + + virtual char const* type_name() const + { + return ""Multi""; + } + + virtual std::string as_string() const + { + return (boost::format( + ""%s(id=%s, event=%s, last_time=%.16g, dt=%.16g, particles=[%s])"") % + type_name() % + boost::lexical_cast(base_type::id_).c_str() % + boost::lexical_cast(base_type::event_.first).c_str() % + base_type::last_time_ % base_type::dt_ % + stringize_and_join( + make_select_first_range(pc_.get_particles_range()), + "", "")).str(); + } + + Multi(identifier_type const& id, simulator_type& main, Real dt_factor) + : base_type(id), main_(main), pc_(*main.world()), dt_factor_(dt_factor), + shells_(), last_event_(NONE) + { + BOOST_ASSERT(dt_factor > 0.); + base_type::dt_ = dt_factor_ * determine_dt(*main_.world()); + // base_type::dt_ = dt_factor_ * BDSimulator::determine_dt(*main_.world()); + } + + static Real determine_dt(world_type const& world) + { + using ecell4::pow_2; + Real D_max(0.), radius_min(std::numeric_limits::max()); + + for(const molecule_info_type& s : world.get_molecule_info_range()) + { + if (D_max < s.D) + { + D_max = s.D; + } + if (radius_min > s.radius) + { + radius_min = s.radius; + } + } + return pow_2(radius_min * 2) / (D_max * 2); + } + + event_kind const& last_event() const + { + return last_event_; + } + + reaction_record_type const& last_reaction() const + { + return last_reaction_; + } + + bool has_particle(particle_id_type const& pid) const + { + return pc_.has_particle(pid); + } + + bool add_particle(particle_id_pair const& pp) + { + return pc_.update_particle(pp.first, pp.second); + } + + bool add_shell(spherical_shell_id_pair const& sp) + { + spherical_shell_id_pair new_sp(sp); + new_sp.second.did() = base_type::id(); + return shells_.insert(new_sp).second; + } + + spherical_shell_id_pair_range get_shells() const + { + return spherical_shell_id_pair_range(shells_.begin(), shells_.end(), shells_.size()); + } + + virtual typename Domain::size_type num_shells() const + { + return shells_.size(); + } + + virtual typename Domain::size_type multiplicity() const + { + return pc_.num_particles(); + } + + virtual void accept(ImmutativeDomainVisitor const& visitor) const + { + visitor(*this); + } + + virtual void accept(MutativeDomainVisitor const& visitor) + { + visitor(*this); + } + + bool within_shell(particle_shape_type const& sphere) const + { + for (const spherical_shell_id_pair& sp : shells_) + { + position_type ppos(main_.world()->periodic_transpose(sphere.position(), (sp).second.position())); + if (ecell4::egfrd::distance(ppos, (sp).second.shape().position()) < + (sp).second.shape().radius() - sphere.radius()) + { + return true; + } + } + return false; + } + + bool clear_volume(particle_shape_type const& shape, particle_id_type const& ignore) const + { + LOG_DEBUG((""clear_volume was called here."")); + main_.clear_volume(shape, base_type::id_); + + const particle_id_pair_and_distance_list overlapped( + main_.world()->check_overlap(shape, ignore)); + if (overlapped.size() > 0) + { + return false; + } + return true; + // return (main_.world()->no_overlap(shape, ignore)); + } + + bool clear_volume(particle_shape_type const& shape, particle_id_type const& ignore0, particle_id_type const& ignore1) const + { + LOG_DEBUG((""clear_volume was called here."")); + main_.clear_volume(shape, base_type::id_); + + const particle_id_pair_and_distance_list overlapped( + main_.world()->check_overlap(shape, ignore0, ignore1)); + if (overlapped.size() > 0) + { + return false; + } + return true; + // return (main_.world()->no_overlap(shape, ignore0, ignore1)); + } + + typename multi_particle_container_type::particle_id_pair_range + get_particles_range() const + { + return pc_.get_particles_range(); + } + + void step() + { + last_reaction_setter rs(*this); + volume_clearer vc(*this); + BDPropagator ppg( + pc_, *main_.network_rules(), main_.rng(), + base_type::dt_, + 1 /* FIXME: dissociation_retry_moves */, &rs, &vc, + make_select_first_range(pc_.get_particles_range())); + + last_event_ = NONE; + + while (ppg()) + { + if (last_reaction_) + { + last_event_ = REACTION; + break; + } + } + } + +protected: + simulator_type& main_; + multi_particle_container_type pc_; + Real dt_factor_; + spherical_shell_map shells_; + event_kind last_event_; + reaction_record_type last_reaction_; + + static Logger& log_; +}; + +template +Logger& Multi::log_(Logger::get_logger(""ecell.Multi"")); + +} // egfrd +} // ecell4 +#endif /* MULTI_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/structures.hpp",".hpp","4939","182","#ifndef ECELL4_EGFRD_STRUCTURES_HPP +#define ECELL4_EGFRD_STRUCTURES_HPP + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct ImmutativeStructureVisitor +{ + typedef Ttraits_ traits_type; + // typedef typename traits_type::spherical_surface_type spherical_surface_type; + // typedef typename traits_type::cylindrical_surface_type cylindrical_surface_type; + // typedef typename traits_type::planar_surface_type planar_surface_type; + typedef typename traits_type::cuboidal_region_type cuboidal_region_type; + + virtual ~ImmutativeStructureVisitor() {} + + // virtual void operator()(spherical_surface_type const&) const = 0; + // virtual void operator()(cylindrical_surface_type const&) const = 0; + // virtual void operator()(planar_surface_type const&) const = 0; + virtual void operator()(cuboidal_region_type const&) const = 0; +}; + +template +struct MutativeStructureVisitor +{ + typedef Ttraits_ traits_type; + // typedef typename traits_type::spherical_surface_type spherical_surface_type; + // typedef typename traits_type::cylindrical_surface_type cylindrical_surface_type; + // typedef typename traits_type::planar_surface_type planar_surface_type; + typedef typename traits_type::cuboidal_region_type cuboidal_region_type; + + virtual ~MutativeStructureVisitor() {} + + // virtual void operator()(spherical_surface_type&) const = 0; + // virtual void operator()(cylindrical_surface_type&) const = 0; + // virtual void operator()(planar_surface_type&) const = 0; + virtual void operator()(cuboidal_region_type&) const = 0; +}; + +template +class Structure +{ +public: + + typedef Ttraits_ traits_type; + typedef typename traits_type::structure_id_type identifier_type; + typedef typename traits_type::length_type length_type; + typedef typename traits_type::position_type position_type; + typedef RandomNumberGenerator rng_type; + +public: + + Structure(const identifier_type& id) + : id_(id) + { + ; + } + + virtual ~Structure() + { + ; // do nothing + } + + const identifier_type& id() const + { + return id_; + } + + virtual position_type random_vector(length_type const& r, rng_type& rng) const = 0; + virtual position_type bd_displacement(length_type const& r, rng_type& rng) const = 0; + + virtual void accept(ImmutativeStructureVisitor const& visitor) const = 0; + // virtual void accept(MutativeStructureVisitor const& visitor) = 0; + +protected: + + identifier_type id_; +}; + +template +class ShapedStructure + : public Structure +{ +public: + + typedef Structure base_type; + typedef Tshape_ shape_type; + + typedef typename base_type::traits_type traits_type; + typedef typename base_type::identifier_type identifier_type; + typedef typename base_type::length_type length_type; + typedef typename base_type::position_type position_type; + typedef typename base_type::rng_type rng_type; + +public: + + ShapedStructure(const identifier_type& id, const shape_type& shape) + : base_type(id), shape_(shape) + { + ; + } + + shape_type& shape() + { + return shape_; + } + + const shape_type& shape() const + { + return shape_; + } + +protected: + + shape_type shape_; +}; + +template +class AABBRegion + : public ShapedStructure //XXX +{ +public: + + typedef ShapedStructure base_type; + + typedef typename base_type::traits_type traits_type; + typedef typename base_type::shape_type shape_type; + typedef typename base_type::identifier_type identifier_type; + typedef typename base_type::length_type length_type; + typedef typename base_type::position_type position_type; + typedef typename base_type::rng_type rng_type; + +public: + + AABBRegion(const identifier_type& id, const shape_type& shape) + : base_type(id, shape) + { + ; + } + + virtual ~AABBRegion() + { + ; + } + + virtual position_type random_vector(length_type const& r, rng_type& rng) const + { + // return rng.direction3d(r); + return normalize( + create_vector( + rng.uniform(-1., 1.), rng.uniform(-1., 1.), rng.uniform(-1., 1.)), + r); + } + + virtual position_type bd_displacement(length_type const& r, rng_type& rng) const + { + return create_vector( + rng.gaussian(r), rng.gaussian(r), rng.gaussian(r)); + } + + virtual void accept(ImmutativeStructureVisitor const& visitor) const + { + visitor(*this); + } + + // virtual void accept(MutativeStructureVisitor const& visitor) + // { + // visitor(*this); + // } +}; + +} // egfrd +} // ecell4 + +#endif /* ECELL4_STRUCTURES_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/twofold_container.hpp",".hpp","6355","292","#ifndef ECELL4_EGFRD_TWOFOLD_CONTAINER_HPP +#define ECELL4_EGFRD_TWOFOLD_CONTAINER_HPP + +#include +#include +#include +#include +#include ""utils/memberwise_compare.hpp"" + +namespace ecell4 +{ +namespace egfrd +{ + +inline bool is_initialized(std::string const &obj) +{ + return (0 < obj.size()); +} + +inline bool is_initialized(ecell4::Species const &obj) +{ + return (0 < obj.serial().size()); +} + +template +bool is_initialized(T const &obj) +{ + return obj.is_initialized(); +} + +template +class twofold_container +{ +public: + typedef T_ value_type; +private: + typedef std::array containing_type; +public: + typedef typename containing_type::reference reference; + typedef typename containing_type::const_reference const_reference; + typedef typename containing_type::size_type size_type; + typedef typename containing_type::difference_type difference_type; + + class const_iterator; + class iterator + : public boost::iterator_facade< + iterator, value_type, boost::forward_traversal_tag> + { + friend class const_iterator; + friend class twofold_container; + friend class boost::iterator_core_access; + + std::ptrdiff_t distance_to(iterator const& that) const + { + return that.idx_ - idx_; + } + + bool equal(iterator const& that) const + { + return &cntnr_ == &that.cntnr_ && idx_ == that.idx_; + } + + void increment() + { + ++idx_; + } + + value_type& dereference() const + { + return cntnr_[idx_]; + } + + public: + iterator(twofold_container& cntnr, size_type idx) + : cntnr_(cntnr), idx_(idx) {} + + iterator(const_iterator const& that) + : cntnr_(const_cast(that.cntnr_)), + idx_(that.idx_) + {} + + private: + twofold_container& cntnr_; + size_type idx_; + }; + + class const_iterator + : public boost::iterator_facade< + const_iterator, const value_type, boost::forward_traversal_tag> + { + friend class iterator; + friend class twofold_container; + friend class boost::iterator_core_access; + + std::ptrdiff_t distance_to(const_iterator const& that) const + { + return that.idx_ - idx_; + } + + bool equal(const_iterator const& that) const + { + return &cntnr_ == &that.cntnr_ && idx_ == that.idx_; + } + + void increment() + { + ++idx_; + } + + value_type const& dereference() const + { + return cntnr_[idx_]; + } + + public: + const_iterator(twofold_container const& cntnr, size_type idx) + : cntnr_(cntnr), idx_(idx) {} + + const_iterator(iterator const& that) + : cntnr_(that.cntnr_), idx_(that.idx_) {} + + private: + twofold_container const& cntnr_; + size_type idx_; + }; + +public: + twofold_container() + { + items_[0] = value_type(); + items_[1] = value_type(); + } + + twofold_container(value_type const& one) + { + BOOST_ASSERT(one); + items_[0] = one; + items_[1] = value_type(); + } + + twofold_container(value_type const& one, value_type const& two) + { + BOOST_ASSERT(one); + BOOST_ASSERT(two); + if (one <= two) + { + items_[0] = one; + items_[1] = two; + } + else + { + items_[0] = two; + items_[1] = one; + } + } + + size_type size() const + { + return is_initialized(items_[0]) ? is_initialized(items_[1]) ? 2: 1: 0; + } + + iterator begin() + { + return iterator(*this, 0); + } + + iterator end() + { + return iterator(*this, size()); + } + + const_iterator begin() const + { + return const_iterator(*this, 0); + } + + const_iterator end() const + { + return const_iterator(*this, size()); + } + + void push_back(value_type const& item) + { + if (!is_initialized(items_[0])) + { + items_[0] = item; + } + else if (!is_initialized(items_[1])) + { + items_[1] = item; + } + else + { + BOOST_ASSERT(false); + } + } + + iterator insert(iterator pos, value_type const& item) + { + switch (pos.idx_) + { + case 0: + switch (size()) + { + case 0: + items_[0] = item; + return pos; + case 1: + items_[1] = items_[0]; + items_[0] = item; + return pos; + default: + break; + } + case 1: + switch (size()) + { + case 1: + items_[1] = item; + return pos; + default: + break; + } + } + BOOST_ASSERT(0); + } + + value_type& operator[](std::size_t idx) + { + return items_[idx]; + } + + value_type const& operator[](std::size_t idx) const + { + return items_[idx]; + } + + bool operator<(twofold_container const& rhs) const + { + return memberwise_compare(*this, rhs) < 0; + } + + bool operator>=(twofold_container const& rhs) const + { + return !operator<(rhs); + } + + bool operator>(twofold_container const& rhs) const + { + return memberwise_compare(*this, rhs) > 0; + } + + bool operator<=(twofold_container const& rhs) const + { + return !operator>(rhs); + } + + bool operator==(twofold_container const& rhs) const + { + if (rhs.size() != size()) + return false; + switch (size()) + { + case 0: + return true; + case 1: + return items_[0] == rhs[0]; + case 2: + return items_[0] == rhs[0] && items_[1] == rhs[1]; + } + /* never get here */ + return false; + } + + bool operator!=(twofold_container const& rhs) const + { + return !operator==(rhs); + } + + void swap(twofold_container& rhs) + { + std::swap(items_, rhs.items_); + } + +protected: + containing_type items_; +}; + +} // egfrd +} // ecell4 +#endif /* TWOFOLD_CONTAINER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/array_helper.hpp",".hpp","662","34","#ifndef ECELL4_EGFRD_UTILS_ARRAY_HELPER_HPP +#define ECELL4_EGFRD_UTILS_ARRAY_HELPER_HPP +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +inline std::array array_gen() +{ + return std::array{}; +} +template +inline std::array array_gen(const T& v0) +{ + return std::array{{v0}}; +} +template +inline std::array array_gen(const T& v0, const T& v1) +{ + return std::array{{v0, v1}}; +} +template +inline std::array array_gen(const T& v0, const T& v1, const T& v2) +{ + return std::array{{v0, v1, v2}}; +} + +} // egfrd +} // ecell4 +#endif /* ARRAY_HELPER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/array_traits.hpp",".hpp","245","14","#ifndef ECELL4_EGFRD_UTILS_ARRAY_TRAITS_HPP +#define ECELL4_EGFRD_UTILS_ARRAY_TRAITS_HPP + +namespace ecell4 +{ +namespace egfrd +{ +template< typename T_ > +struct element_type_of{}; + +} // ecell4 +} // egfrd +#endif// ECELL4_EGFRD_UTILS_ARRAY_TRAITS_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/range.hpp",".hpp","7463","258","#ifndef ECELL4_EGFRD_UTILS_RANGE_HPP +#define ECELL4_EGFRD_UTILS_RANGE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +using iterator_category = typename std::iterator_traits::type>::iterator_category; + +template +struct check_range_iterator_category + : std::is_convertible< + typename boost::iterator_category_to_traversal< + typename boost::iterator_traversal::type>::type >::type, + typename boost::iterator_category_to_traversal::type > {}; + +template +struct is_sized + : check_range_iterator_category +{ +}; + +template +struct range_size: boost::range_difference {}; + +template +struct range_size_retriever +{ + typedef Trange_ argument_type; + typedef typename range_size::type result_type; + + result_type operator()(argument_type const& range) const + { + return boost::size(range); + } +}; + +template +inline typename range_size::type +size(Trange_ const& r) +{ + return range_size_retriever()(r); +} + +template +class sized_iterator_range: public boost::iterator_range +{ + typedef boost::iterator_range base_type; + +public: + sized_iterator_range(): size_(0) {} + + template + sized_iterator_range(Taiter_ begin, Taiter_ end) + : base_type(begin, end), size_(end - begin) {} + + template + sized_iterator_range(Trange_ const& r) + : base_type(r), size_(ecell4::egfrd::size(r)) {} + + template + sized_iterator_range(Trange_& r) + : base_type(r), size_(ecell4::egfrd::size(r)) {} + + template + sized_iterator_range(Taiter_ begin, Taiter_ end, + typename base_type::size_type size) + : base_type(begin, end), size_(size) {} + + template + sized_iterator_range(Trange_ const& r, typename base_type::size_type size) + : base_type(r), size_(size) {} + + template + sized_iterator_range(Trange_& r, typename base_type::size_type size) + : base_type(r), size_(size) {} + + typename base_type::size_type size() const + { + return size_; + } + +private: + typename base_type::size_type size_; +}; + +template +struct is_sized >: std::true_type +{ +}; + +template +struct range_size > +{ + typedef std::size_t type; +}; + +template +struct range_size_retriever > +{ + typedef sized_iterator_range argument_type; + typedef typename range_size::type result_type; + + result_type operator()(argument_type const& range) const + { + return range.size(); + } +}; + +namespace detail { + +template >, + is_sized >::value> +struct get_default_range_holder +{ + template + struct apply + { + typedef boost::iterator_range type; + }; +}; + +template +struct get_default_range_holder +{ + template + struct apply + { + typedef sized_iterator_range type; + }; +}; + +} // namespace detail + +template > +class transformed_range +{ +public: + typedef Titer_ base_iterator; + typedef Tfun_ functor_type; + typedef boost::transform_iterator iterator; + typedef typename Tholder_getter_::template apply::type holder_type; + typedef iterator const_iterator; + typedef typename boost::iterator_value::type value_type; + typedef typename boost::iterator_difference::type difference_type; + typedef std::size_t size_type; + typedef typename boost::iterator_reference::type reference; + typedef reference const_reference; + +public: + template + transformed_range(Trange& range, Tfun_ const& fun) + : base_(range), fun_(fun) {} + + template + transformed_range(Trange const& range, Tfun_ const& fun) + : base_(range), fun_(fun) {} + + holder_type base() const + { + return base_; + } + + iterator begin() const + { + return iterator(boost::begin(base_), fun_); + } + + iterator end() const + { + return iterator(boost::end(base_), fun_); + } + + size_type size() const + { + return ecell4::egfrd::size(base_); + } + + reference operator[](size_type idx) const + { + return fun_()(base_[idx]); + } + +private: + holder_type base_; + functor_type fun_; +}; + +template +struct get_transformed_range +{ + typedef transformed_range::type, Tfun_, detail::get_default_range_holder > type; +}; + +template +struct get_transformed_range +{ + typedef transformed_range::type, Tfun_, detail::get_default_range_holder > type; +}; + +template +inline typename get_transformed_range::type +make_transform_iterator_range(Trange_ const& range, Tfun_ const& fun) +{ + typedef typename get_transformed_range::type transformed_range; + return transformed_range(range, fun); +} + +template +inline typename get_transformed_range::type +make_transform_iterator_range(Trange_ const& range, Tfun_ const& fun, bool) +{ + typedef typename get_transformed_range::type transformed_range; + return transformed_range(range, fun); +} + +template +struct range_size >: public range_size::type> {}; + + +template +struct is_sized >: public is_sized::type> {}; + +template +struct range_size_retriever > +{ + typedef transformed_range argument_type; + typedef typename range_size::type>::type result_type; + + result_type operator()(argument_type const& range) const + { + return range.size(); + } +}; + +} // egfrd +} // ecell4 +#endif /* UTILS_RANGE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/memberwise_compare.hpp",".hpp","1297","44","#ifndef ECELL4_EGFRD_UTILS_MEMBERWISE_COMPARE_HPP +#define ECELL4_EGFRD_UTILS_MEMBERWISE_COMPARE_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +inline int memberwise_compare(Tlhs_ const& lhs, Trhs_ const& rhs) +{ + typedef typename boost::range_const_iterator::type lhs_iterator; + typedef typename boost::range_const_iterator::type rhs_iterator; + + if (boost::size(lhs) <= boost::size(rhs)) + { + std::pair pair( + std::mismatch(lhs.begin(), lhs.end(), rhs.begin())); + if (pair.first == lhs.end()) + return boost::size(lhs) - boost::size(rhs); + return *pair.first < *pair.second ? -1: + *pair.first > *pair.second ? 1: 0; + } + else if (boost::size(lhs) > boost::size(rhs)) + { + std::pair pair( + std::mismatch(rhs.begin(), rhs.end(), lhs.begin())); + if (pair.first == rhs.end()) + return 1; + return *pair.first < *pair.second ? 1: + *pair.first > *pair.second ? -1: 0; + } + return 0; +} + +} // egfrd +} // ecell4 +#endif /* MEMBERWISE_COMPARE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/collection_contains.hpp",".hpp","435","22","#ifndef ECELL4_EGFRD_UTILS_COLLECTION_CONTAINS_HPP +#define ECELL4_EGFRD_UTILS_COLLECTION_CONTAINS_HPP + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +inline bool collection_contains(T_ const& s, typename T_::value_type const& v) +{ + auto e(std::end(s)); + return e != std::find(std::begin(s), e, v); +} + +} // egfrd +} // ecell4 +#endif /* ECELL4_EGFRD_COLLECTION_CONTAINS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/random.hpp",".hpp","591","28","#ifndef ECELL4_EGFRD_UTILS_RANDOM_HPP +#define ECELL4_EGFRD_UTILS_RANDOM_HPP + +#include +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +inline void shuffle(Trng_& rng, Tracntnr_& cntnr) +{ + typedef typename boost::range_size::type size_type; + for (size_type i = boost::size(cntnr); i > 0;) + { + --i; + const size_type j(rng.uniform_int(0, i)); + std::swap(cntnr[i], cntnr[j]); + } +} + +} // egfrd +} // ecell4 +#endif /* UTILS_RANDOM_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/fun_composition.hpp",".hpp","942","46","#ifndef ECELL4_EGFRD_UTILS_FUN_COMPOSITION_HPP +#define ECELL4_EGFRD_UTILS_FUN_COMPOSITION_HPP +#include + +namespace ecell4 +{ +namespace egfrd +{ + +namespace detail +{ +template +struct fun_compose_impl +{ + using result_type = typename F1::result_type; + + fun_compose_impl(const F1& f1, const F2& f2): f1_(f1), f2_(f2) {} + + template + result_type operator()(Args&& ... args) const + { + return f1_( f2_(std::forward(args)...) ); + } + + template + result_type operator()(Args&& ... args) + { + return f1_( f2_(std::forward(args)...) ); + } + +private: + F1 f1_; + F2 f2_; +}; +} // namespace detail + +template +inline detail::fun_compose_impl fun_composition(const F1& f1, const F2& f2) +{ + return detail::fun_compose_impl(f1, f2); +} + +} // egfrd +} // ecell4 +#endif /* FUN_COMPOSITION_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/stringizer.hpp",".hpp","734","28","#ifndef ECELL4_EGFRD_UTILS_STRINGIZER_HPP +#define ECELL4_EGFRD_UTILS_STRINGIZER_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +std::string stringize_and_join(const Range& range, const std::string& separator) +{ + using value_type = typename boost::range_value::type; + + return boost::algorithm::join(boost::adaptors::transform(range, + [](const value_type& v) -> std::string { + return boost::lexical_cast(v); + }), separator); +} + +} // egfrd +} // ecell4 +#endif /* ECELL4_EGFRD_UTILS_STRINGIZER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/pointer_as_ref.hpp",".hpp","951","63","#ifndef ECELL4_EGFRD_UTILS_POINTER_AS_REF_HPP +#define ECELL4_EGFRD_UTILS_POINTER_AS_REF_HPP + +#include + +namespace ecell4 +{ +namespace egfrd +{ + +template +struct pointer_as_ref +{ + typedef T_ element_type; + typedef T_* holder_type; + + operator T_&() const { return *ptr_; } + + T_& operator=(element_type const& val) const + { + *ptr_ = val; + return *ptr_; + } + + T_* get() const + { + return ptr_; + } + + void set(T_* ptr) + { + ptr_ = ptr; + } + + operator bool() const + { + return !!ptr_; + } + + explicit pointer_as_ref(holder_type ptr) + : ptr_(ptr) {} + + explicit pointer_as_ref(): ptr_(0) {} + +private: + holder_type ptr_; +}; + +} // egfrd +} // ecell4 + +namespace boost { + +template +inline T* get_pointer(ecell4::egfrd::pointer_as_ref const& p) +{ + return p.get(); +} + +} // namespace boost + +#endif /* UTILS_POINTER_AS_REF_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/math.hpp",".hpp","870","33","#ifndef ECELL4_EGFRD_UTILS_MATH_HPP +#define ECELL4_EGFRD_UTILS_MATH_HPP + +#include +#include + +namespace ecell4 +{ +namespace egfrd +{ +/** + * Return True if a and b are equal, subject to given tolerances. Float + * comparison. + * + * See also numpy.allclose(). + * + * The (relative) tolerance must be positive and << 1.0 + * + * Instead of specifying an absolute tolerance, you can speciy a typical + * value for a or b. The absolute tolerance is then the relative tolerance + * multipied by this typical value, and will be used when comparing a value + * to zero. By default, the typical value is 1. + */ +template +inline bool feq(T const& a, T const& b, T const& typical = 1., double tolerance = 1e-7) +{ + return std::abs(a - b) <= tolerance * (typical + std::min(std::abs(a), std::abs(b))); +} + +} // egfrd +} // ecell4 +#endif /* UTILS_MATH_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/utils/pair.hpp",".hpp","2740","102","#ifndef ECELL4_EGFRD_UTILS_PAIR_HPP +#define ECELL4_EGFRD_UTILS_PAIR_HPP + +#include +#include +#include ""range.hpp"" + +// --------------------------------------------------------------------------- +// functors to extract first/second element of std::pair + +namespace ecell4 +{ +namespace egfrd +{ + +template < typename T_ > +struct select_first +{ + typedef T_ argument_type; + typedef typename T_::first_type result_type; + + typename T_::first_type& operator()( T_& pair ) const + { + return pair.first; + } + + typename T_::first_type const& operator()( T_ const& pair ) const + { + return pair.first; + } +}; + +template < typename T_ > +struct select_second +{ + typedef T_ argument_type; + typedef typename T_::second_type result_type; + + typename T_::second_type& operator()( T_& pair ) const + { + return pair.second; + } + + typename T_::second_type const& operator()( T_ const& pair ) const + { + return pair.second; + } +}; + +// -------------------------------------------------------------------------- +// helper aliases + +template +using select_first_range_t = boost::transformed_range< + select_first::type>, Trange_>; + +template +using select_second_range_t = boost::transformed_range< + select_second::type>, Trange_>; + +// -------------------------------------------------------------------------- +// make_select_first_range + +template +inline select_first_range_t +make_select_first_range(Trange_& range) +{ + using value_type = typename boost::range_value::type; + return boost::adaptors::transform(range, select_first()); +} + +template +inline select_first_range_t +make_select_first_range(Trange_ const& range) +{ + using value_type = typename boost::range_value::type; + return boost::adaptors::transform(range, select_first()); +} + +// -------------------------------------------------------------------------- +// make_select_second_range + +template +inline select_second_range_t +make_select_second_range(Trange_& range) +{ + using value_type = typename boost::range_value::type; + return boost::adaptors::transform(range, select_second()); +} + +template +inline select_second_range_t +make_select_second_range(Trange_ const& range) +{ + using value_type = typename boost::range_value::type; + return boost::adaptors::transform(range, select_second()); +} + +} // egfrd +} // ecell4 +#endif /* UTILS_PAIR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/samples/mymapk.cpp",".cpp","8730","245","// vim: foldmethod=marker +// Sakamoto EPDP Sample + +#include +#include +#include +#include + +#include +#include + +#include + +// // epdp headers +// #include +// #include +// #include +// //#include +// //#include +// //#include +// //#include +// //#include +// //#include +// #include +// //#include +// //#include + +#include +#include +#include +#include +#include + +#include + + +// typedef double Real; + +int main(int argc, char **argv) +{ + // Traits typedefs + // {{{ + // typedef ::World< ::CyclicWorldTraits > world_type; + // typedef EGFRDSimulator< ::EGFRDSimulatorTraitsBase > + // simulator_type; + typedef ecell4::egfrd::EGFRDWorld world_type; + typedef ecell4::egfrd::DefaultEGFRDSimulator simulator_type; + typedef simulator_type::multi_type multi_type; + // }}} + + // Constants + // {{{ + const ecell4::Real L(1e-6); + const ecell4::Real3 edge_lengths(L, L, L); + const ecell4::Integer3 matrix_sizes(3, 3, 3); + const ecell4::Real volume(L * L * L); + const ecell4::Integer N(60); + const ecell4::Real kd(0.1), U(0.5); + const ecell4::Real ka(kd * volume * (1 - U) / (U * U * N)); + const ecell4::Real k2(ka), k1(kd); + const ecell4::Integer dissociation_retry_moves(3); + // }}} + + std::shared_ptr + model(new ecell4::NetworkModel()); + + // add ::SpeciesType to ::ParticleModel + // {{{ + ecell4::Species sp1( + std::string(""A""), 2.5e-09, 1e-12); + model->add_species_attribute(sp1); + + ecell4::Species sp2( + std::string(""B""), 2.5e-09, 1e-12); + model->add_species_attribute(sp2); + + ecell4::Species sp3( + std::string(""C""), 2.5e-09, 1e-12); + model->add_species_attribute(sp3); + // }}} + + // ReactionRules + // {{{ + // A -> B + C k1 + // {{{ + ecell4::ReactionRule rr1( + ecell4::create_unbinding_reaction_rule(sp1, sp2, sp3, k1)); + model->add_reaction_rule(rr1); + // }}} + + // B + C -> A k2 + // {{{ + ecell4::ReactionRule rr2( + ecell4::create_binding_reaction_rule(sp2, sp3, sp1, k2)); + model->add_reaction_rule(rr2); + // }}} + // }}} + + // Random Number Generator (Instanciate and Initialize) + // {{{ + // std::shared_ptr + std::shared_ptr + rng(new ecell4::GSLRandomNumberGenerator()); + rng->seed((unsigned long int)0); + // rng->seed(time(NULL)); + // }}} + + // World Definition + // {{{ + std::shared_ptr + world(new world_type(edge_lengths, matrix_sizes, rng)); + world->bind_to(model); + // }}} + + // add ecell4::Species( ::SpeciesInfo) to ::World + // {{{ + // world->add_species(ecell4::Species(""A"")); + // world->add_species(ecell4::Species(""B"")); + // world->add_species(ecell4::Species(""C"")); + // }}} + + // Thorow particles into world at random + // {{{ + world->add_molecules(ecell4::Species(""A""), N); + + typedef std::vector > + particle_id_pair_list; + const particle_id_pair_list particles(world->list_particles()); + for (particle_id_pair_list::const_iterator i(particles.begin()); + i != particles.end(); ++i) + { + const ecell4::Real3 pos((*i).second.position()); + std::cout << ""("" << pos[0] << pos[1] << pos[2] << "")"" << std::endl; + } + // }}} + + // Logger Settings + // {{{ + std::shared_ptr logger_mng( + new ecell4::egfrd::LoggerManager(""dummy"", ecell4::egfrd::Logger::L_WARNING)); + ecell4::egfrd::LoggerManager::register_logger_manager( + ""ecell.EGFRDSimulator"", logger_mng); + // }}} + + // EGFRDSimulator instance generated + // {{{ + std::shared_ptr sim( + new simulator_type(world, model, dissociation_retry_moves)); + // sim->paranoiac() = true; + sim->initialize(); + // }}} + + // Simulation Executed + // {{{ + ecell4::Real next_time(0.0), dt(0.02); + std::cout << sim->t() << ""\t"" + << world->num_molecules_exact(sp1) << ""\t"" + << world->num_molecules_exact(sp2) << ""\t"" + << world->num_molecules_exact(sp3) << ""\t"" << std::endl; + // for (int i(0); i < 10; i++) + // for (int i(0); i < 100; i++) + for (int i(0); i < 100; i++) + { + next_time += dt; + while (sim->step(next_time)) + { + // if (sim->last_reactions().size() > 0) + // { + // std::cout << sim->t() << ""\t"" + // << world->num_molecules_exact(sp1) << ""\t"" + // << world->num_molecules_exact(sp2) << ""\t"" + // << world->num_molecules_exact(sp3) << ""\t"" << std::endl; + // } + } + + std::cout << sim->t() << ""\t"" + << world->num_molecules_exact(sp1) << ""\t"" + << world->num_molecules_exact(sp2) << ""\t"" + << world->num_molecules_exact(sp3) << ""\t"" << std::endl; + } + // }}} + + // world->save(""test.h5""); + + // Statistics + // {{{ + int num_single_steps_per_type[simulator_type::NUM_SINGLE_EVENT_KINDS]; + num_single_steps_per_type[simulator_type::SINGLE_EVENT_REACTION] + = sim->num_single_steps_per_type(simulator_type::SINGLE_EVENT_REACTION); + num_single_steps_per_type[simulator_type::SINGLE_EVENT_ESCAPE] + = sim->num_single_steps_per_type(simulator_type::SINGLE_EVENT_ESCAPE); + + std::cout << (boost::format(""%1%: %2% \n"") + % ""SINGLE_EVENT_REACTION"" + % num_single_steps_per_type[simulator_type::SINGLE_EVENT_REACTION]); + std::cout << (boost::format(""%1%: %2% \n"") + % ""SINGLE_EVENT_ESCAPE"" + % num_single_steps_per_type[simulator_type::SINGLE_EVENT_ESCAPE]); + + std::cout << (boost::format(""%1%: %2% \n"") + % ""PAIR_EVENT_SINGLE_REACTION_0"" + % sim->num_pair_steps_per_type( + simulator_type::PAIR_EVENT_SINGLE_REACTION_0)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""PAIR_EVENT_SINGLE_REACTION_1"" + % sim->num_pair_steps_per_type( + simulator_type::PAIR_EVENT_SINGLE_REACTION_1)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""PAIR_EVENT_COM_ESCAPE"" + % sim->num_pair_steps_per_type(simulator_type::PAIR_EVENT_COM_ESCAPE)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""PAIR_EVENT_IV_UNDETERMINED"" + % sim->num_pair_steps_per_type( + simulator_type::PAIR_EVENT_IV_UNDETERMINED)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""PAIR_EVENT_IV_ESCAPE"" + % sim->num_pair_steps_per_type(simulator_type::PAIR_EVENT_IV_ESCAPE)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""PAIR_EVENT_IV_REACTION"" + % sim->num_pair_steps_per_type(simulator_type::PAIR_EVENT_IV_REACTION)); + + std::cout << (boost::format(""%1%: %2% \n"") + % ""NONE"" % sim->num_multi_steps_per_type(multi_type::NONE)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""ESCAPE"" % sim->num_multi_steps_per_type(multi_type::ESCAPE)); + std::cout << (boost::format(""%1%: %2% \n"") + % ""REACTION"" % sim->num_multi_steps_per_type(multi_type::REACTION)); + // }}} + + // { + // std::unique_ptr + // world2(new world_type(ecell4::Real3(1, 2, 3), ecell4::Integer3(3, 6, 9))); + // std::cout << ""edge_lengths:"" << world2->edge_lengths()[0] << "" "" << world2->edge_lengths()[1] << "" "" << world2->edge_lengths()[2] << std::endl; + // std::cout << ""matrix_sizes:"" << world2->matrix_sizes()[0] << "" "" << world2->matrix_sizes()[1] << "" "" << world2->matrix_sizes()[2] << std::endl; + // std::cout << ""num_particles: "" << world2->num_particles() << std::endl; + + // world2->load(""test.h5""); + // std::cout << ""edge_lengths:"" << world2->edge_lengths()[0] << "" "" << world2->edge_lengths()[1] << "" "" << world2->edge_lengths()[2] << std::endl; + // std::cout << ""matrix_sizes:"" << world2->matrix_sizes()[0] << "" "" << world2->matrix_sizes()[1] << "" "" << world2->matrix_sizes()[2] << std::endl; + // std::cout << ""num_particles: "" << world2->num_particles() << std::endl; + // } + + return 0; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/samples/polygon.cpp",".cpp","7095","206","// vim: foldmethod=marker +// copied from Sakamoto EPDP Sample, mymapk +// remove reaction, change output format to xyz, and add polygon structure. + +#include +#include +#include +#include +#include +#include + +#include + +// // epdp headers +// #include +// #include +// #include +// //#include +// //#include +// //#include +// //#include +// //#include +// //#include +// #include +// //#include +// //#include + +#include +#include +#include +#include +#include +#include + +#include + + +// typedef double Real; + +int main(int argc, char **argv) +{ + // Traits typedefs + // {{{ + // typedef ::World< ::CyclicWorldTraits > world_type; + // typedef EGFRDSimulator< ::EGFRDSimulatorTraitsBase > + // simulator_type; + typedef ecell4::egfrd::EGFRDWorld world_type; + typedef ecell4::egfrd::DefaultBDSimulator simulator_type; +// typedef simulator_type::multi_type multi_type; + // }}} + + // Constants + // {{{ + const ecell4::Real L(1e2); + const ecell4::Real3 edge_lengths(L, L, L); + const ecell4::Integer3 matrix_sizes(3, 3, 3); + // const ecell4::Real volume(L * L * L); + const ecell4::Integer N(60); + // const ecell4::Real kd(0.1), U(0.5); + // const ecell4::Real ka(kd * volume * (1 - U) / (U * U * N)); + // const ecell4::Real k2(ka), k1(kd); + // }}} + + std::shared_ptr + model(new ecell4::NetworkModel()); + + // add ::SpeciesType to ::ParticleModel + // {{{ + ecell4::Species sp1( + std::string(""C""), 2.5, 1e3); + model->add_species_attribute(sp1); + ecell4::Species sp2( + std::string(""N""), 2.5, 1e3); + model->add_species_attribute(sp2); + + // }}} + + // ReactionRules + // {{{ + // Nothing! + // }}} + + // Random Number Generator (Instanciate and Initialize) + // {{{ + // std::shared_ptr + std::shared_ptr + rng(new ecell4::GSLRandomNumberGenerator()); + rng->seed((unsigned long int)0); + // rng->seed(time(NULL)); + // }}} + + // Read Polygon from an STL file + // {{{ + std::cerr << ""polygon setup begin"" << std::endl; + + ecell4::Polygon poly = ecell4::read_polygon( + ""sphere_radius_24_center_50.stl"", ecell4::STLFormat::Ascii, + edge_lengths); + + std::cerr << ""polygon setup end"" << std::endl; + // }}} + + // World Definition + // {{{ + std::shared_ptr + world(new world_type(edge_lengths, matrix_sizes, rng, poly)); + world->bind_to(model); + // }}} + + std::cerr << ""particle generate start"" << std::endl; + // Throw particles into world at random + // {{{ + for(std::size_t i=0; iuniform(0, 15.0); +// const ecell4::Real theta = rng->uniform(0, 2.0 * 3.14159265358979); +// const ecell4::Real phi = rng->uniform(0, 2.0 * 3.14159265358979); + const ecell4::Real3 sphere_center(50.0, 50.0, 50.0); +// const ecell4::Real3 dist( +// radius * sin(theta) * cos(phi), +// radius * sin(theta) * sin(phi), +// radius * cos(theta)); +// assert(length(dist) < 24.); + const ecell4::Real3 position(rng->uniform(0.0, 1e2), rng->uniform(0.0, 1e2), rng->uniform(0.0, 1e2)); + ecell4::Particle newpart; + if(length(position - sphere_center) < 20.0) + newpart = ecell4::Particle(ecell4::Species(""C""), position, 2.5, 1e3); + else if(length(position - sphere_center) > 30) + newpart = ecell4::Particle(ecell4::Species(""N""), position, 2.5, 1e3); + else + continue; + if(world->new_particle(newpart).second) break; + } + } + std::cerr << ""particle generate end"" << std::endl; + // }}} + + // Logger Settings + // {{{ + std::shared_ptr logger_mng( + new ecell4::egfrd::LoggerManager(""dummy"", ecell4::egfrd::Logger::L_WARNING)); + ecell4::egfrd::LoggerManager::register_logger_manager( + ""ecell.EGFRDSimulator"", logger_mng); + // }}} + + // EGFRDSimulator instance generated + // {{{ + std::shared_ptr sim( + new simulator_type(world, model, 1.0)); + // sim->paranoiac() = true; + sim->initialize(); + // }}} + + std::cerr << ""simulation start"" << std::endl; + // Simulation Executed + // {{{ + ecell4::Real next_time(0.0), dt(0.2); + for (int i(0); i < 100; i++) + { + ecell4::Integer num_sp1 = world->num_molecules_exact(sp1); + ecell4::Integer num_sp2 = world->num_molecules_exact(sp2); + std::cout << num_sp1 + num_sp2 << std::endl; + std::cout << ""now t = "" << sim->t() << std::endl; + const std::vector< + std::pair + > particles = world->list_particles(); + for(std::size_t i=0; i< particles.size(); ++i) + { + const ecell4::Real3 center(50.0, 50.0, 50.0); + if(particles.at(i).second.sid() == ""C"") + { + if(length(particles.at(i).second.position() - center) > 24.) + { + std::cerr << ""radius = "" << length(particles.at(i).second.position() - center) << std::endl; + std::cerr << ""it should be inside"" << std::endl; +// assert(false); + } + } + else if(particles.at(i).second.sid() == ""N"") + { + if(length(particles.at(i).second.position() - center) < 24.) + { + std::cerr << ""radius = "" << length(particles.at(i).second.position() - center) << std::endl; + std::cerr << ""it should be outside"" << std::endl; +// assert(false); + } + } +// if(length(particles.at(i).second.position() - center) > 24.) +// { +// std::cerr << ""particle goes out!"" << std::endl; +// } + std::cout << particles.at(i).second.sid() << "" "" + << particles.at(i).second.position()[0] << "" "" + << particles.at(i).second.position()[1] << "" "" + << particles.at(i).second.position()[2] << std::endl; + } + next_time += dt; + while (sim->step(next_time)){} + } + // }}} + + return 0; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/egfrd/tests/GreensFunction3DRadInf_test.cpp",".cpp","947","39","#define BOOST_TEST_MODULE ""GreensFunction3DRadInf_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include ""../GreensFunction3DRadInf.hpp"" + + +BOOST_AUTO_TEST_CASE(GreensFunction3DRadInf_test_constructor) +{ + const Real D = 2e-12; + const Real kf = 0; + const Real r0 = 1.0084e-08; + const Real sigma = 1e-08; + + GreensFunction3DRadInf gf(D, kf, r0, sigma); +} + +// BOOST_AUTO_TEST_CASE(GreensFunction3DRadInf_test_drawTheta) +// { +// const Real D = 2e-12; +// const Real kf = 0; +// const Real r0 = 1.0084e-08; +// const Real sigma = 1e-08; +// +// GreensFunction3DRadInf gf(D, kf, r0, sigma); +// +// const Real r = 1.11944e-08; +// const Real t = 5.08006e-08; +// const Real rnd = 0.5; //XXX +// +// const Real theta = gf.drawTheta(rnd, r, t); +// BOOST_CHECK(theta >= 0); +// } +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/WorldInterface.hpp",".hpp","5438","208","#ifndef ECELL4_WORLD_INTERFACE_HPP +#define ECELL4_WORLD_INTERFACE_HPP + +#include + +#include ""exceptions.hpp"" +#include ""types.hpp"" +#include ""Real3.hpp"" +#include ""Species.hpp"" +#include ""Particle.hpp"" + +#include + +namespace ecell4 +{ + +struct WorldInterface +{ + virtual ~WorldInterface() + { + ; // do nothing + } + + // virtual const Real t() const = 0; //XXX: This doesn't work with Python35 MSVC2015 + virtual const Real t() const + { + return 0.0; //XXX: Just for debugging + } + + virtual void set_t(const Real& t) = 0; + + //XXX: This doesn't work with Python35 MSVC2015 + // virtual void save(const std::string& filename) const + // { + // throw NotSupported( + // ""save(const std::string) is not supported by this space class""); + // } + virtual void save(const std::string& filename) const = 0; + + virtual void load(const std::string& filename) + { + throw NotSupported( + ""load(const std::string) is not supported by this space class""); + } + + /** + * get volume. + * @return a volume (m^3) Real + */ + virtual const Real volume() const + { + throw NotSupported(""volume() is not supported by this space class""); + } + + // /** + // * get the number of species in this space. + // * @return a number of species Integer + // */ + // virtual Integer num_species() const + // { + // throw NotSupported(""num_species() is not supported by this space class""); + // } + + /** + * return if the species is in this space or not. + * @param sp a species + * @return if the species is in this space + */ + virtual bool has_species(const Species& sp) const + { + throw NotSupported( + ""has_species(const Species&) is not supported by this space class""); + } + + virtual std::vector list_species() const + { + throw NotSupported( + ""list_species() is not supported by this space class""); + } + + /** + * get the number of molecules + * @param sp a species + * @return a number of molecules Integer + */ + virtual Integer num_molecules(const Species& sp) const + { + throw NotSupported( + ""num_molecules(const Species&) is not supported"" + "" by this space class""); + } + + virtual Integer num_molecules_exact(const Species& sp) const + { + throw NotSupported( + ""num_molecules_exact(const Species&) is not supported"" + "" by this space class""); + } + + virtual Real get_value(const Species& sp) const + { + throw NotSupported( + ""get_value(const Species&) is not supported"" + "" by this space class""); + } + + virtual Real get_value_exact(const Species& sp) const + { + throw NotSupported( + ""get_value_exact(const Species&) is not supported"" + "" by this space class""); + } + + /** + * get the axes lengths of a cuboidal region. + * @return edge lengths Real3 + */ + virtual const Real3& edge_lengths() const + { + throw NotSupported( + ""edge_lengths() is not supported by this space class""); + } + + /** + * get the number of particles. + * @return a number of particles Integer + */ + virtual Integer num_particles() const + { + throw NotSupported( + ""num_particles() is not supported by this space class""); + } + + /** + * get the number of particles. + * @param sp a species + * @return a number of particles Integer + */ + virtual Integer num_particles(const Species& sp) const + { + throw NotSupported( + ""num_particles(const Species&) is not supported"" + "" by this space class""); + } + + virtual Integer num_particles_exact(const Species& sp) const + { + throw NotSupported( + ""num_particles_exact(const Species&) is not supported"" + "" by this space class""); + } + + /** + * check if the particle exists. + * @param pid an ID for the particle + * @return if the particle exists or not bool + */ + virtual bool has_particle(const ParticleID& pid) const + { + throw NotSupported( + ""has_particle(const ParticleID&) is not supported"" + "" by this space class""); + } + + virtual std::pair get_particle(const ParticleID& pid) const + { + throw NotSupported( + ""get_particle(const ParticleID&) is not supported"" + "" by this space class""); + } + + /** + * get all particles. + * @return a list of particles + */ + virtual std::vector > + list_particles() const + { + throw NotSupported( + ""list_particles() is not supported by this space class.""); + } + + /** + * get particles. + * @param sp a species + * @return a list of particles + */ + virtual std::vector > + list_particles(const Species& sp) const + { + throw NotSupported( + ""list_particles(const Species&) is not supported"" + "" by this space class""); + } + + virtual std::vector > + list_particles_exact(const Species& sp) const + { + throw NotSupported( + ""list_particles_exact(const Species&) is not supported"" + "" by this space class""); + } +}; + +} // ecell4 + +#endif /* ECELL4_WORLD_INTERFACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/comparators.hpp",".hpp","2105","96","#ifndef ECELL4_COMPARATORS_HPP +#define ECELL4_COMPARATORS_HPP + +namespace ecell4 +{ + +namespace utils +{ + +template +struct pair_first_element_unary_predicator +{ + typedef std::pair element_type; + + pair_first_element_unary_predicator(const Tfirst_& target) + : target_(target) + { + ; // do nothing + } + + bool operator()(const element_type& v) + { + return v.first == target_; + } + +protected: + + Tfirst_ target_; +}; + +template +struct pair_second_element_unary_predicator +{ + typedef std::pair element_type; + + pair_second_element_unary_predicator(const Tsecond_& target) + : target_(target) + { + ; // do nothing + } + + bool operator()(const element_type& v) + { + return v.second == target_; + } + +protected: + + Tsecond_ target_; +}; + +template +struct pair_first_element_binary_predicator + : public std::binary_function< + std::pair, std::pair, bool> +{ + typedef std::pair element_type; + + bool operator()(const element_type& v1, const element_type& v2) + { + return v1.first == v2.first; + } +}; + +template +struct pair_first_element_comparator + : public std::binary_function< + std::pair, std::pair, bool> +{ + typedef std::pair element_type; + + inline bool operator()(const element_type& v1, const element_type& v2) + { + return v1.first < v2.first; + } +}; + +template +struct pair_second_element_comparator + : public std::binary_function< + std::pair, std::pair, bool> +{ + typedef std::pair element_type; + + inline bool operator()(const element_type& v1, const element_type& v2) + { + return v1.second < v2.second; + } +}; + +} // utils + +} // ecell4 + +#endif /* ECELL4_COMPARATORS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Journal.cpp",".cpp","1348","84","#include +#include + +#include ""Journal.hpp"" + + +namespace ecell4 +{ + +Journal::Journal(char const* name) + : name_(name) +{ + ; +} + +Journal::~Journal() +{ + ; +} + +void Journal::level(enum Journal::level level) +{ + ensure_initialized(); + level_ = level; +} + +enum Journal::level Journal::level() const +{ + const_cast(this)->ensure_initialized(); + return level_; +} + +void Journal::logv(enum level lv, char const* format, va_list ap) +{ + ensure_initialized(); + + if (lv < level_) + return; + + using namespace std; + + char buf[1024]; + vsnprintf(buf, sizeof(buf), format, ap); + + std::fprintf(stderr, ""%s: %-8s "", name_.c_str(), stringize_error_level(lv)); + std::fwrite(buf, sizeof(char), std::strlen(buf), stderr); + std::fputc('\n', stderr); +} + +void Journal::flush() +{ + ensure_initialized(); + + std::fflush(stderr); +} + +char const* Journal::stringize_error_level(enum level lv) +{ + static char const* names[] = { + ""OFF"", + ""DEBUG"", + ""INFO"", + ""WARN"", + ""ERROR"", + ""FATAL"" + }; + + return (static_cast(lv) >= sizeof(names) / sizeof(*names) + ? ""???"": names[lv]); +} + + +// Journal& Journal::get_journal(char const* name) +// { +// ; +// } + +inline void Journal::ensure_initialized() +{ + ; // not implemented yet +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/PlanarSurface.cpp",".cpp","2066","86","#include ""PlanarSurface.hpp"" +#include ""collision.hpp"" + +namespace ecell4 +{ + +PlanarSurface::PlanarSurface() + : origin_(0, 0, 0), e0_(1, 0, 0), e1_(0, 1, 0), n_(0, 0, 1), d_(0.0) +{ + ; +} + +PlanarSurface::PlanarSurface( + const Real3& origin, const Real3& e0, const Real3& e1) + : origin_(origin), e0_(e0), e1_(e1) +{ + n_ = cross_product(e0_, e1_); + n_ /= length(n_); + d_ = dot_product(origin_, n_); +} + +PlanarSurface::PlanarSurface(const PlanarSurface& rhs) + : origin_(rhs.origin_), e0_(rhs.e0_), e1_(rhs.e1_), n_(rhs.n_), d_(rhs.d_) +{ + ; +} + +Real PlanarSurface::is_inside(const Real3& coord) const +{ + return d_ - dot_product(coord, n_); +} + +Real3 PlanarSurface::draw_position( + std::shared_ptr& rng) const +{ + const Real a(rng->uniform(0, 1)), + b(rng->uniform(0, 1)); + return origin_ + e0_ * a + e1_ * b; +} + +bool PlanarSurface::test_AABB(const Real3& lower, const Real3& upper) const +{ + return collision::test_AABB_plane(AABB(lower, upper), *this); +} + +void PlanarSurface::bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const +{ + constexpr double epsilon = std::numeric_limits::epsilon(); + if (n_[0] > epsilon) + { + lower[0] = std::max( + (d_ - n_[1] * edge_lengths[1] - n_[2] * edge_lengths[2]) / n_[0], 0.0); + upper[0] = std::min(d_ / n_[0], edge_lengths[0]); + } + else + { + lower[0] = 0.0; + upper[0] = edge_lengths[0]; + } + if (n_[1] > epsilon) + { + lower[1] = std::max( + (d_ - n_[0] * edge_lengths[0] - n_[2] * edge_lengths[2]) / n_[1], 0.0); + upper[1] = std::min(d_ / n_[1], edge_lengths[1]); + } + else + { + lower[1] = 0.0; + upper[1] = edge_lengths[1]; + } + if (n_[2] > epsilon) + { + lower[2] = std::max( + (d_ - n_[1] * edge_lengths[1] - n_[0] * edge_lengths[0]) / n_[2], 0.0); + upper[2] = std::min(d_ / n_[2], edge_lengths[2]); + } + else + { + lower[2] = 0.0; + upper[2] = edge_lengths[2]; + } +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ReactionRuleDescriptor.hpp",".hpp","7104","270","#ifndef ECELL4_REACTION_RULE_DESCRIPTOR_HPP +#define ECELL4_REACTION_RULE_DESCRIPTOR_HPP + +#include +#include +#include + +#include ""types.hpp"" +#include ""Species.hpp"" + +#include ""boost/tuple/tuple.hpp"" +#include ""boost/tuple/tuple_io.hpp"" + + +namespace ecell4 +{ + +class ReactionRuleDescriptor +{ +public: + + typedef std::vector reactant_container_type; + typedef std::vector product_container_type; + typedef std::vector coefficient_container_type; + + typedef std::vector state_container_type; + + // The following stores propensity_func, number of reactant coefficients, number of product_coefficients + typedef boost::tuple descriptor_attribute; + +public: + + ReactionRuleDescriptor(const coefficient_container_type &reactant_coefficients, const coefficient_container_type &product_coefficients) + : reactant_coefficients_(reactant_coefficients), product_coefficients_(product_coefficients) + { + ; + } + + ReactionRuleDescriptor() + { + ; + } + + virtual ~ReactionRuleDescriptor() + { + ; + } + + virtual bool is_available() const + { + return true; + } + + descriptor_attribute attribute(void) const + { + return boost::make_tuple( + this->is_available(), reactant_coefficients_.size(), product_coefficients_.size()); + } + + virtual Real propensity(const state_container_type& r, const state_container_type& p, Real volume, Real time) const = 0; + + virtual ReactionRuleDescriptor* clone() const + { + return 0; + } + + // Accessor of coefficients; + const coefficient_container_type &reactant_coefficients(void) const + { + return this->reactant_coefficients_; + } + + const coefficient_container_type &product_coefficients(void) const + { + return this->product_coefficients_; + } + + void resize_reactants(const std::size_t size) + { + this->reactant_coefficients_.resize(size, 1.0); + } + + void resize_products(const std::size_t size) + { + this->product_coefficients_.resize(size, 1.0); + } + + void set_reactant_coefficient(const std::size_t num, const Real new_coeff) + { + if (num >= reactant_coefficients_.size()) + { + this->resize_reactants(num + 1); + } + this->reactant_coefficients_[num] = new_coeff; + } + + void set_product_coefficient(const std::size_t num, const Real new_coeff) + { + if (num >= product_coefficients_.size()) + { + this->resize_products(num + 1); + } + this->product_coefficients_[num] = new_coeff; + } + + void set_reactant_coefficients(const coefficient_container_type &new_reactant_coefficients) + { + this->reactant_coefficients_.clear(); + for (coefficient_container_type::size_type i = 0; i < new_reactant_coefficients.size(); i++) + { + this->reactant_coefficients_.push_back(new_reactant_coefficients[i]); + } + } + + void set_product_coefficients(const coefficient_container_type &new_product_coefficients) + { + this->product_coefficients_.clear(); + for (coefficient_container_type::size_type i = 0; i < new_product_coefficients.size(); i++) + { + this->product_coefficients_.push_back(new_product_coefficients[i]); + } + } + + bool has_coefficients(void) const + { + return !(this->reactant_coefficients_.empty() && this->product_coefficients_.empty()); + } + +private: + + coefficient_container_type reactant_coefficients_; + coefficient_container_type product_coefficients_; +}; + +class ReactionRuleDescriptorMassAction + : public ReactionRuleDescriptor +{ +public: + + typedef ReactionRuleDescriptor base_type; + typedef base_type::state_container_type state_container_type; + +public: + + ReactionRuleDescriptorMassAction(const Quantity& k) + : base_type(), k_(k) + { + ; + } + + ReactionRuleDescriptorMassAction(const Quantity& k, const coefficient_container_type &reactant_coefficients, const coefficient_container_type &product_coefficients) + : base_type(reactant_coefficients, product_coefficients), k_(k) + { + ; + } + + ReactionRuleDescriptorMassAction(const Real k) + : base_type(), k_(k) + { + ; + } + + ReactionRuleDescriptorMassAction(const Real k, const coefficient_container_type &reactant_coefficients, const coefficient_container_type &product_coefficients) + : base_type(reactant_coefficients, product_coefficients), k_(k) + { + ; + } + + virtual ReactionRuleDescriptor* clone() const + { + return new ReactionRuleDescriptorMassAction(k_, reactant_coefficients(), product_coefficients()); + } + + const Real k() const + { + return k_.magnitude; + } + + Quantity get_k() const + { + return k_; + } + + void set_k(const Real k) + { + k_ = Quantity(k); + } + + void set_k(const Quantity& k) + { + k_ = k; + } + + virtual Real propensity(const state_container_type& reactants, const state_container_type& products, Real volume, Real t) const + { + Real ret = k_.magnitude * volume; + state_container_type::const_iterator i(reactants.begin()); + coefficient_container_type::const_iterator j(reactant_coefficients().begin()); + for (; i != reactants.end() && j != reactant_coefficients().end(); ++i, ++j) + { + ret *= std::pow((*i) / volume, (*j)); + } + return ret; + } + +private: + + Quantity k_; +}; + +class ReactionRuleDescriptorCPPfunc + : public ReactionRuleDescriptor +{ +public: + + typedef ReactionRuleDescriptor base_type; + typedef base_type::state_container_type state_container_type; + typedef Real (*func_type)(const state_container_type& r, const state_container_type& p, Real volume, Real t, const ReactionRuleDescriptorCPPfunc& rd); + +public: + + ReactionRuleDescriptorCPPfunc(func_type pf) + : base_type(), pf_(pf) + { + ; + } + + ReactionRuleDescriptorCPPfunc(func_type pf, const coefficient_container_type &reactant_coefficients, const coefficient_container_type &product_coefficients) + : base_type(reactant_coefficients, product_coefficients), pf_(pf) + { + ; + } + + virtual ReactionRuleDescriptor* clone() const + { + return new ReactionRuleDescriptorCPPfunc(pf_, reactant_coefficients(), product_coefficients()); + } + + bool is_available() const + { + return (this->pf_ != 0); + } + + func_type get() const + { + return this->pf_; + } + + virtual Real propensity(const state_container_type& reactants, const state_container_type& products, Real volume, Real time) const + { + if (this->is_available()) + { + return (this->pf_)(reactants, products, volume, time, *this); + } + else + { + // throw IllegalState(""Pointer to the user-defined propensity function is NULL""); + return 0.0; + } + } + +private: + + func_type pf_; +}; + +} // ecell4 + +#endif /* ECELL4_REACTION_RULE_DESCRIPTOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/exceptions.hpp",".hpp","3117","219","#ifndef ECELL4_EXCEPTIONS_HPP +#define ECELL4_EXCEPTIONS_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ + +class Exception + : public std::exception +{ +public: + + Exception() + { + ; + } + + virtual ~Exception() throw() + { + ; + } + + virtual const char* what() const throw() + { + return """"; + } +}; + +class NotFound + : public Exception +{ +public: + + NotFound(const std::string& str) + : str_(str) + { + ; + } + + virtual ~NotFound() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +class AlreadyExists + : public Exception +{ +public: + + AlreadyExists(const std::string& str) + : str_(str) + { + ; + } + + virtual ~AlreadyExists() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +class NotImplemented + : public Exception +{ +public: + + NotImplemented(const std::string& str) + : str_(str) + { + ; + } + + virtual ~NotImplemented() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +class NotSupported + : public Exception +{ +public: + + NotSupported(const std::string& str) + : str_(str) + { + ; + } + + virtual ~NotSupported() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +class IllegalState + : public Exception +{ +public: + + IllegalState(const std::string& str) + : str_(str) + { + ; + } + + virtual ~IllegalState() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +class IllegalArgument + : public Exception +{ +public: + + IllegalArgument(const std::string& str) + : str_(str) + { + ; + } + + + virtual ~IllegalArgument() throw() + { + ; + } + + virtual const char* what() const throw() + { + return str_.c_str(); + } + +private: + + std::string str_; +}; + +namespace detail +{ +inline std::string concat_arguments_to_string_impl(std::ostringstream& oss) +{ + return oss.str(); +} +template +std::string concat_arguments_to_string_impl( + std::ostringstream& oss, T&& head, Ts&& ... tail) +{ + oss << std::forward(head); + return concat_arguments_to_string_impl(oss, std::forward(tail)...); +} +template +std::string concat_arguments_to_string(Ts&& ... args) +{ + std::ostringstream oss; + return concat_arguments_to_string_impl(oss, std::forward(args)...); +} +} // detail + +template +[[noreturn]] void throw_exception(Ts&& ... args) +{ + throw Exception(detail::concat_arguments_to_string(std::forward(args)...)); +} + +} // ecell4 +#endif /* ECELL4_EXCEPTIONS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpaceCellListImpl.cpp",".cpp","10611","347","#include ""ParticleSpaceCellListImpl.hpp"" +#include ""Context.hpp"" +#include ""comparators.hpp"" + + +namespace ecell4 +{ + +void ParticleSpaceCellListImpl::reset(const Real3& edge_lengths) +{ + base_type::t_ = 0.0; + particles_.clear(); + rmap_.clear(); + particle_pool_.clear(); + + for (matrix_type::size_type i(0); i < matrix_.shape()[0]; ++i) + { + for (matrix_type::size_type j(0); j < matrix_.shape()[1]; ++j) + { + for (matrix_type::size_type k(0); k < matrix_.shape()[2]; ++k) + { + matrix_[i][j][k].clear(); + } + } + } + + for (Real3::size_type dim(0); dim < 3; ++dim) + { + if (edge_lengths[dim] <= 0) + { + throw std::invalid_argument(""the edge length must be positive.""); + } + } + + edge_lengths_ = edge_lengths; + // throw NotImplemented(""Not implemented yet.""); +} + +bool ParticleSpaceCellListImpl::update_particle( + const ParticleID& pid, const Particle& p) +{ + particle_container_type::iterator i(find(pid)); + if (i != particles_.end()) + { + if ((*i).second.species() != p.species()) + { + particle_pool_[(*i).second.species_serial()].erase((*i).first); + particle_pool_[p.species_serial()].insert(pid); + } + this->update(i, std::make_pair(pid, p)); + return false; + } + + this->update(std::make_pair(pid, p)); + // const bool succeeded(this->update(std::make_pair(pid, p)).second); + // BOOST_ASSERT(succeeded); + + particle_pool_[p.species_serial()].insert(pid); + return true; +} + +std::pair ParticleSpaceCellListImpl::get_particle( + const ParticleID& pid) const +{ + particle_container_type::const_iterator i(this->find(pid)); + if (i == particles_.end()) + { + throw NotFound(""No such particle.""); + } + return (*i); +} + +bool ParticleSpaceCellListImpl::has_particle(const ParticleID& pid) const +{ + return (this->find(pid) != particles_.end()); +} + +void ParticleSpaceCellListImpl::remove_particle(const ParticleID& pid) +{ + //XXX: In contrast to the original ParticleContainer in epdp, + //XXX: this remove_particle throws an error when no corresponding + //XXX: particle is found. + std::pair pp(get_particle(pid)); //XXX: may raise an error. + particle_pool_[pp.second.species_serial()].erase(pid); + this->erase(pid); +} + +Integer ParticleSpaceCellListImpl::num_particles() const +{ + return particles_.size(); +} + +Integer ParticleSpaceCellListImpl::num_particles(const Species& sp) const +{ + Integer retval(0); + SpeciesExpressionMatcher sexp(sp); + for (per_species_particle_id_set::const_iterator i(particle_pool_.begin()); + i != particle_pool_.end(); ++i) + { + const Species tgt((*i).first); + if (sexp.match(tgt)) + { + retval += (*i).second.size(); + } + } + return retval; +} + +Integer ParticleSpaceCellListImpl::num_particles_exact(const Species& sp) const +{ + per_species_particle_id_set::const_iterator i(particle_pool_.find(sp.serial())); + if (i == particle_pool_.end()) + { + return 0; + } + return (*i).second.size(); +} + +Integer ParticleSpaceCellListImpl::num_molecules(const Species& sp) const +{ + Integer retval(0); + SpeciesExpressionMatcher sexp(sp); + for (per_species_particle_id_set::const_iterator i(particle_pool_.begin()); + i != particle_pool_.end(); ++i) + { + const Species tgt((*i).first); + retval += sexp.count(tgt) * (*i).second.size(); + } + return retval; +} + +Integer ParticleSpaceCellListImpl::num_molecules_exact(const Species& sp) const +{ + return num_particles_exact(sp); +} + +std::vector > + ParticleSpaceCellListImpl::list_particles() const +{ + return particles_; +} + +std::vector > + ParticleSpaceCellListImpl::list_particles(const Species& sp) const +{ + std::vector > retval; + SpeciesExpressionMatcher sexp(sp); + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + if (sexp.match((*i).second.species())) + { + retval.push_back(*i); + } + } + return retval; +} + +std::vector > + ParticleSpaceCellListImpl::list_particles_exact(const Species& sp) const +{ + std::vector > retval; + + // per_species_particle_id_set::const_iterator + // i(particle_pool_.find(sp.serial())); + // if (i == particle_pool_.end()) + // { + // //XXX: In the original, this raises an error, + // //XXX: but returns an empty vector here. + // return retval; + // } + // retval.reserve((*i).second.size()); + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + if ((*i).second.species() == sp) + { + retval.push_back(*i); + } + } + return retval; +} + +std::vector, Real> > + ParticleSpaceCellListImpl::list_particles_within_radius( + const Real3& pos, const Real& radius) const +{ + std::vector, Real> > retval; + + // MatrixSpace::each_neighbor_cyclic + if (particles_.size() == 0) + { + return retval; + } + + cell_index_type idx(this->index(pos)); + + // MatrixSpace::each_neighbor_cyclic_loops + cell_offset_type off; + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type newidx(idx); + const Real3 stride(this->offset_index_cyclic(newidx, off)); + const cell_type& c(this->cell(newidx)); + for (cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + // neighbor_filter::operator() + particle_container_type::const_iterator + itr(particles_.begin() + (*i)); + // particle_container_type::const_iterator itr = particles_.begin(); + // std::advance(itr, *i); + + const Real dist( + length((*itr).second.position() + stride - pos) + - (*itr).second.radius()); + if (dist < radius) + { + // overlap_checker::operator() + retval.push_back( + std::make_pair(*itr, dist)); + } + } + } + } + } + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>()); + return retval; +} + +std::vector, Real> > + ParticleSpaceCellListImpl::list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore) const +{ + std::vector, Real> > retval; + + // MatrixSpace::each_neighbor_cyclic + if (particles_.size() == 0) + { + return retval; + } + + cell_index_type idx(this->index(pos)); + + // MatrixSpace::each_neighbor_cyclic_loops + cell_offset_type off; + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type newidx(idx); + const Real3 stride(this->offset_index_cyclic(newidx, off)); + const cell_type& c(this->cell(newidx)); + for (cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + // neighbor_filter::operator() + particle_container_type::const_iterator + itr(particles_.begin() + (*i)); + + const Real dist( + length((*itr).second.position() + stride - pos) + - (*itr).second.radius()); + if (dist < radius) + { + // overlap_checker::operator() + if ((*itr).first != ignore) + { + retval.push_back( + std::make_pair(*itr, dist)); + } + } + } + } + } + } + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>()); + return retval; +} + +std::vector, Real> > + ParticleSpaceCellListImpl::list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const +{ + std::vector, Real> > retval; + + // MatrixSpace::each_neighbor_cyclic + if (particles_.size() == 0) + { + return retval; + } + + cell_index_type idx(this->index(pos)); + + // MatrixSpace::each_neighbor_cyclic_loops + cell_offset_type off; + for (off[2] = -1; off[2] <= 1; ++off[2]) + { + for (off[1] = -1; off[1] <= 1; ++off[1]) + { + for (off[0] = -1; off[0] <= 1; ++off[0]) + { + cell_index_type newidx(idx); + const Real3 stride(this->offset_index_cyclic(newidx, off)); + const cell_type& c(this->cell(newidx)); + for (cell_type::const_iterator i(c.begin()); i != c.end(); ++i) + { + // neighbor_filter::operator() + particle_container_type::const_iterator + itr(particles_.begin() + (*i)); + + const Real dist( + length((*itr).second.position() + stride - pos) + - (*itr).second.radius()); + if (dist < radius) + { + // overlap_checker::operator() + if ((*itr).first != ignore1 && (*itr).first != ignore2) + { + retval.push_back( + std::make_pair(*itr, dist)); + } + } + } + } + } + } + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>()); + return retval; +} + +}; +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/extras.cpp",".cpp","8717","273","#include ""extras.hpp"" +#include ""exceptions.hpp"" +#include +#include +#include + + +namespace ecell4 +{ + +namespace extras +{ + +Shape::dimension_kind +get_dimension_from_model(const Species& species, const std::shared_ptr& model) +{ + const Shape::dimension_kind DEFAULT_DIMENSION(Shape::THREE); + + if (species.serial().empty()) + return DEFAULT_DIMENSION; + + if (!model->has_species_attribute(species)) + { + // std::stringstream ss; + // ss << ""The model has no attribute for Specis(\"""" << species.serial() << ""\"")""; + // throw NotFound(ss.str()); + return DEFAULT_DIMENSION; + } + + const Species& attribute(model->apply_species_attributes(species)); + + if (attribute.has_attribute(""dimension"")) + { + switch (attribute.get_attribute_as(""dimension"")) + { + case 1: return Shape::ONE; + case 2: return Shape::TWO; + case 3: return Shape::THREE; + } + } + + if (attribute.has_attribute(""location"")) + { + return get_dimension_from_model( + Species(attribute.get_attribute_as(""location"")), + model + ); + } + + return DEFAULT_DIMENSION; +} + +#ifdef WITH_HDF5 +void save_version_information(H5::H5Location* root, const std::string& version) +{ + if (version.size() > 32) + { + throw IllegalArgument(""Version info must be shorter than 32 characters.""); + } + using namespace H5; + std::unique_ptr dataset( + new DataSet(root->createDataSet(""version"", H5::StrType(H5::PredType::C_S1, 32), H5::DataSpace(H5S_SCALAR)))); + dataset->write(version.c_str(), dataset->getDataType()); +} + +std::string load_version_information(const H5::H5Location& root) +{ + using namespace H5; + char buf[32]; + const DataSet dataset(DataSet(root.openDataSet(""version""))); + dataset.read(buf, dataset.getDataType()); + return std::string(buf); +} +#endif + +std::string load_version_information(const std::string& filename) +{ +#ifdef WITH_HDF5 + using namespace H5; + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + return load_version_information(*fin); +#else + return """"; +#endif +} + +template +T mystoi(const std::string& s) +{ + std::stringstream ss; + ss << s; + T retval; + ss >> retval; + return retval; +} + +std::pair parse_prerelease(const std::string& prestr) +{ + if (prestr.size() == 0) + { + return std::make_pair(VersionInformation::FINAL, 0); + } + else if (prestr[0] == 'a') + { + return std::make_pair(VersionInformation::ALPHA, mystoi(prestr.substr(1))); + } + else if (prestr[0] == 'b') + { + return std::make_pair(VersionInformation::BETA, mystoi(prestr.substr(1))); + } + else if (prestr[0] == 'c') + { + return std::make_pair(VersionInformation::RC, mystoi(prestr.substr(1))); + } + else if (prestr.size() >= 2 && prestr[0] == 'r' && prestr[1] == 'c') + { + return std::make_pair(VersionInformation::RC, mystoi(prestr.substr(2))); + } + else + { + throw NotSupported(""Unknown pre-release was given.""); + return std::make_pair(VersionInformation::NONE, 0); + } +} + +VersionInformation parse_version_information(const std::string& version) +{ + using namespace std; + + regex reg(""^([^-\\.]+-[^-\\.]+-)([0123456789]+)\\.([0123456789]+)(\\.[0123456789]+|)(a[0123456789]+|b[0123456789]+|rc[0123456789]+|c[0123456789]+|)(\\.dev[0123456789]+|)$""); + smatch result; + if (!regex_match(version, result, reg)) + { + throw std::invalid_argument( + ""a wrong version information was given ["" + version + ""]""); //XXX: + } + + const std::string header = result.str(1); + const unsigned int majorno = mystoi(result.str(2)); + const unsigned int minorno = mystoi(result.str(3)); + const unsigned int patchno = (result.str(4).size() > 1 ? mystoi(result.str(4).substr(1)) : 0); + const std::pair pre = parse_prerelease(result.str(5)); + const int devno = (result.str(6).size() > 4 ? mystoi(result.str(6).substr(4)) : -1); + + return VersionInformation(header, majorno, minorno, patchno, pre.first, pre.second, devno); + +} + +bool check_version_information(const std::string& version, const std::string& required) +{ + const VersionInformation vinfo1(parse_version_information(version)); + const VersionInformation vinfo2(parse_version_information(required)); + + if (vinfo1.header != vinfo2.header) + { + return false; + } + else if (vinfo1.majorno != vinfo2.majorno) + { + return (vinfo1.majorno > vinfo2.majorno); + } + else if (vinfo1.minorno != vinfo2.minorno) + { + return (vinfo1.minorno > vinfo2.minorno); + } + else if (vinfo1.patchno != vinfo2.patchno) + { + return (vinfo1.patchno > vinfo2.patchno); + } + else if (vinfo1.pre != vinfo2.pre) + { + return (vinfo1.pre > vinfo2.pre); + } + else if (vinfo1.preno != vinfo2.preno) + { + return (vinfo1.preno > vinfo2.preno); + } + return (vinfo1.devno == -1 || (vinfo2.devno != -1 && vinfo1.devno >= vinfo2.devno)); +} + +std::vector > get_stoichiometry( + const std::vector& species_list, const std::vector& reaction_rules) +{ + typedef std::unordered_map species_map_type; + + species_map_type index_map; + { + unsigned i(0); + for(std::vector::const_iterator it(species_list.begin()); + it != species_list.end(); it++, i++) + { + index_map[*it] = i; + } + } + + std::vector > ret; + { + ret.resize(species_list.size()); + for (std::vector >::iterator it(ret.begin()); + it != ret.end(); ++it) + { + (*it).resize(reaction_rules.size()); + } + + unsigned i(0); + for (std::vector::const_iterator it(reaction_rules.begin()); + it != reaction_rules.end(); ++it, i++) + { + const ReactionRule& rr(*it); + + if (!rr.has_descriptor()) + { + for (auto const& sp : rr.reactants()) + { + ret[index_map[sp]][i] -= 1.0; + } + for (auto const& sp : rr.products()) + { + ret[index_map[sp]][i] += 1.0; + } + } + else + { + const std::shared_ptr& desc(rr.get_descriptor()); + { + if (rr.reactants().size() != desc->reactant_coefficients().size()) + { + std::stringstream msg; + msg << ""The number of reactant coefficients mismatches ("" + << desc->reactant_coefficients().size() + << "" != "" + << rr.reactants().size() + << "").""; + throw std::runtime_error(msg.str()); + } + + ReactionRule::reactant_container_type::const_iterator it1(rr.reactants().begin()); + ReactionRuleDescriptor::coefficient_container_type::const_iterator it2(desc->reactant_coefficients().begin()); + for (; it1 != rr.reactants().end(); ++it1, ++it2) + { + ret[index_map[(*it1)]][i] -= (*it2); + } + } + { + if (rr.products().size() != desc->product_coefficients().size()) + { + std::stringstream msg; + msg << ""The number of product coefficients mismatches ("" + << desc->product_coefficients().size() + << "" != "" + << rr.products().size() + << "").""; + throw std::runtime_error(msg.str()); + } + + ReactionRule::product_container_type::const_iterator it1(rr.products().begin()); + ReactionRuleDescriptor::coefficient_container_type::const_iterator it2(desc->product_coefficients().begin()); + for (; it1 != rr.products().end(); ++it1, ++it2) + { + ret[index_map[(*it1)]][i] += (*it2); + } + } + } + } + } + return ret; +} + +} // extras + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/SerialIDGenerator.hpp",".hpp","8301","361","#ifndef ECELL4_SERIAL_ID_GENERATOR_HPP +#define ECELL4_SERIAL_ID_GENERATOR_HPP + +#include +#include +#include + +#include + +#ifdef WITH_HDF5 +#include +#include +#endif + + +namespace ecell4 +{ + +namespace detail +{ + +template +struct identifier_lot_helper +{ + typedef typename Tid_::lot_type type; +}; + +template +struct identifier_lot_helper +{ + typedef Tid_ type; +}; + +template +struct identifier_lot_adder_helper + : public std::binary_function +{ + Tid_ operator()(const Tid_& lhs, typename Tid_::lot_type rhs) + { + return lhs.lot_add(rhs); + } +}; + +template +struct identifier_lot_adder_helper + : public std::binary_function +{ + Tid_ operator()(const Tid_& lhs, const Tid_& rhs) + { + return lhs + rhs; + } +}; + +template +struct identifier_lot_advancer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const typename Tid_::lot_type& rhs) + { + lhs.lot_advance(rhs); + return lhs; + } +}; + +template +struct identifier_lot_advancer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const Tid_& rhs) + { + lhs += rhs; + return lhs; + } +}; + +template +struct identifier_lot_retracer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const typename Tid_::lot_type& rhs) + { + lhs.lot_retrace(rhs); + return lhs; + } +}; + +template +struct identifier_lot_retracer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const Tid_& rhs) + { + lhs -= rhs; + return lhs; + } +}; + +template +struct identifier_lot_retriever_helper + : public std::binary_function +{ + const typename identifier_lot_helper::type& + operator()(const Tid_& lhs) + { + return lhs.lot(); + } +}; + +template +struct identifier_lot_retriever_helper + : public std::binary_function +{ + typename identifier_lot_helper::type& operator()(Tid_& lhs) + { + return lhs; + } +}; + +template +struct identifier_serial_helper +{ + typedef typename Tid_::serial_type type; +}; + +template +struct identifier_serial_helper +{ + typedef Tid_ type; +}; + +template +struct identifier_serial_advancer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const typename Tid_::serial_type& rhs) + { + lhs.serial_advance(rhs); + return lhs; + } +}; + +template +struct identifier_serial_advancer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const Tid_& rhs) + { + lhs += rhs; + return lhs; + } +}; + +template +struct identifier_serial_retracer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const typename Tid_::serial_type& rhs) + { + lhs.serial_retrace(rhs); + return lhs; + } +}; + +template +struct identifier_serial_retracer_helper + : public std::binary_function +{ + Tid_& operator()(Tid_& lhs, const Tid_& rhs) + { + lhs -= rhs; + return lhs; + } +}; + +template +struct identifier_serial_retriever_helper + : public std::binary_function +{ + const typename identifier_serial_helper::type& + operator()(const Tid_& lhs) + { + return lhs.serial(); + } +}; + +template +struct identifier_serial_retriever_helper + : public std::binary_function +{ + typename identifier_serial_helper::type& operator()(Tid_& lhs) + { + return lhs; + } +}; + +} // namespace detail + +template +struct identifier_lot + : public detail::identifier_lot_helper::value, Tid_> +{ +}; + +template +struct identifier_lot_adder + : public detail::identifier_lot_adder_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_lot_advancer + : public detail::identifier_lot_advancer_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_lot_retracer + : public detail::identifier_lot_retracer_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_lot_retriever + : public detail::identifier_lot_retriever_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_serial + : public detail::identifier_serial_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_serial_advancer + : public detail::identifier_serial_advancer_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_serial_retracer + : public detail::identifier_serial_retracer_helper< + std::is_integral::value, Tid_> +{ +}; + +template +struct identifier_serial_retriever + : public detail::identifier_serial_retriever_helper< + std::is_integral::value, Tid_> +{ +}; + +template +Tid_ lot_add(const Tid_& lhs, const typename identifier_lot::type& rhs) +{ + return identifier_lot_adder()(lhs, rhs); +} + +template +Tid_& lot_advance(Tid_& lhs, const typename identifier_lot::type& rhs) + +{ + return identifier_lot_advancer()(lhs, rhs); +} + +template +Tid_& lot_retrace(Tid_& lhs, const typename identifier_lot::type& rhs) +{ + return identifier_lot_retracer()(lhs, rhs); +} + +template +typename identifier_lot::type lot(Tid_& lhs) +{ + return identifier_lot_retriever()(lhs); +} + +template +Tid_& serial_advance( + Tid_& lhs, const typename identifier_serial::type& rhs) +{ + return identifier_serial_advancer()(lhs, rhs); +} + +template +Tid_& serial_retrace( + Tid_& lhs, const typename identifier_serial::type& rhs) +{ + return identifier_serial_retracer()(lhs, rhs); +} + +template +typename identifier_serial::type serial(Tid_& lhs) +{ + return identifier_serial_retriever()(lhs); +} + +template +struct SerialIDGenerator +{ +public: + + typedef Tid_ identifier_type; + typedef typename identifier_lot::type lot_type; + +public: + + SerialIDGenerator(const lot_type& lot = lot_type()) + : next_(lot_add(identifier_type(), lot)) + { + ; + } + + identifier_type operator()() + { + return serial_advance(next_, 1); + } + +#ifdef WITH_HDF5 + void save(H5::H5Location* root) const + { + using namespace H5; + + std::unique_ptr optype(new DataType(H5T_OPAQUE, 1)); + hsize_t bufsize(sizeof(identifier_type)); + DataSpace dataspace(1, &bufsize); + optype->setTag(""SerialIDGenerator state type""); + std::unique_ptr dataset( + new DataSet(root->createDataSet(""idgen"", *optype, dataspace))); + dataset->write((unsigned char*)(&next_), *optype); + } + + void load(const H5::H5Location& root) + { + using namespace H5; + + const DataSet dataset(DataSet(root.openDataSet(""idgen""))); + std::unique_ptr optype(new DataType(H5T_OPAQUE, 1)); + optype->setTag(""SerialIDGenerator state type""); + identifier_type state; + dataset.read((unsigned char*)(&state), *optype); + next_ = state; + } +#endif + +private: + + identifier_type next_; +}; + +} // ecell4 + +#endif /* ECELL4_SERIAL_ID_GENERATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/AABB.hpp",".hpp","2031","102","#ifndef ECELL4_AABB_HPP +#define ECELL4_AABB_HPP + +#include ""Shape.hpp"" +#include ""shape_operators.hpp"" + +namespace ecell4 +{ + +struct AABB + : public Shape +{ + AABB() + : lower_(), upper_() + { + ; + } + + AABB(const Real3& lower, const Real3& upper) + : lower_(lower), upper_(upper) + { + ; + } + + AABB(const AABB& rhs) + : lower_(rhs.lower()), upper_(rhs.upper()) + { + ; + } + + const Real3& lower() const throw() + { + return lower_; + } + + const Real3& upper() const throw() + { + return upper_; + } + + // these two modifiers are for boost::geometry::index::rtree. + // see ParticleSpaceRTreeImpl.hpp + Real3& lower() throw() {return lower_;} + Real3& upper() throw() {return upper_;} + + const Real3 center() const + { + return multiply(upper_ + lower_, 0.5); + } + + const Real3 radius() const + { + return multiply(upper_ - lower_, 0.5); + } + + Real distance_sq(const Real3 pos) const; + Real distance(const Real3& pos) const; + + Real is_inside(const Real3& coord) const + { + return distance(coord); + } + + Real3 draw_position( + std::shared_ptr& rng) const; + bool test_AABB(const Real3& l, const Real3& u) const; + bool test_segment(const Real3& p0, const Real3& p1) const; + std::pair intersect_ray(const Real3& p, const Real3& d) const; + + bool test_ray(const Real3& p, const Real3& d) const + { + return intersect_ray(p, d).first; + } + + inline Real3 corner(const int& n) const + { + const Real3 p( + ((n & 1) ? upper_[0] : lower_[0]), + ((n & 2) ? upper_[1] : lower_[1]), + ((n & 4) ? upper_[2] : lower_[2])); + return p; + } + + dimension_kind dimension() const + { + return THREE; + } + + Surface surface() const + { + return Surface(std::shared_ptr(new AABB(*this))); + } + +protected: + + Real3 lower_, upper_; +}; + +}// ecell4 + +#endif /* ECELL4_AABB_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/CompartmentSpace.cpp",".cpp","3800","147","#include +#include + +#include ""exceptions.hpp"" +#include ""functions.hpp"" +#include ""Context.hpp"" +#include ""CompartmentSpace.hpp"" + + +namespace ecell4 +{ + +const Real CompartmentSpaceVectorImpl::volume() const +{ + return volume_; +} + +std::vector CompartmentSpaceVectorImpl::list_species() const +{ + return species_; // return a copy +} + +bool CompartmentSpaceVectorImpl::has_species(const Species& sp) const +{ + return std::find(species_.begin(), species_.end(), sp) != species_.end(); +} + +void CompartmentSpaceVectorImpl::set_volume(const Real& volume) +{ + if (volume <= 0) + { + throw std::invalid_argument(""The volume must be positive.""); + } + + volume_ = volume; + const Real L(cbrt(volume)); + edge_lengths_ = Real3(L, L, L); +} + +void CompartmentSpaceVectorImpl::reserve_species(const Species& sp) +{ + species_map_type::const_iterator i(index_map_.find(sp)); + if (i != index_map_.end()) + { + throw AlreadyExists(""Species already exists""); + } + + index_map_.insert(std::make_pair(sp, num_molecules_.size())); + species_.push_back(sp); + num_molecules_.push_back(0); +} + +void CompartmentSpaceVectorImpl::release_species(const Species& sp) +{ + species_map_type::iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + throw_exception(""Speices ["", sp.serial(), ""] not found""); + } + + species_map_type::mapped_type + idx((*i).second), last_idx(num_molecules_.size() - 1); + if (idx != last_idx) + { + species_container_type::size_type const + idx_(static_cast(idx)), + last_idx_(static_cast(last_idx)); + const Species& last_sp(species_[last_idx_]); + species_[idx_] = last_sp; + num_molecules_[idx] = num_molecules_[last_idx]; + index_map_[last_sp] = idx; + } + + species_.pop_back(); + num_molecules_.pop_back(); + index_map_.erase(sp); +} + +Integer CompartmentSpaceVectorImpl::num_molecules(const Species& sp) const +{ + SpeciesExpressionMatcher sexp(sp); + Integer retval(0); + for (species_map_type::const_iterator i(index_map_.begin()); + i != index_map_.end(); ++i) + { + retval += num_molecules_[(*i).second] * sexp.count((*i).first); + } + return retval; +} + +Integer CompartmentSpaceVectorImpl::num_molecules_exact(const Species& sp) const +{ + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + // throw NotFound(""Species not found""); + return 0; + } + return num_molecules_[(*i).second]; +} + +void CompartmentSpaceVectorImpl::add_molecules( + const Species& sp, const Integer& num) +{ + if (num < 0) + { + throw_exception( + ""The number of molecules must be positive. ["", sp.serial(), ""]""); + } + + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + // throw NotFound(""Species not found""); + reserve_species(sp); + i = index_map_.find(sp); + } + + num_molecules_[(*i).second] += num; +} + +void CompartmentSpaceVectorImpl::remove_molecules( + const Species& sp, const Integer& num) +{ + if (num < 0) + { + throw_exception( + ""The number of molecules must be positive. ["", sp.serial(), ""]""); + } + + species_map_type::const_iterator i(index_map_.find(sp)); + if (i == index_map_.end()) + { + throw_exception(""Speices ["", sp.serial(), ""] not found""); + } + + if (num_molecules_[(*i).second] < num) + { + throw_exception( + ""The number of molecules cannot be negative. ["", sp.serial(), ""]""); + } + + num_molecules_[(*i).second] -= num; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/RandomNumberGenerator.hpp",".hpp","3179","138","#ifndef ECELL4_RANDOM_NUMBER_GENERATOR_HPP +#define ECELL4_RANDOM_NUMBER_GENERATOR_HPP + +#include +#include +#include +#include +#include + +#include ""types.hpp"" +#include ""Real3.hpp"" +#include ""exceptions.hpp"" + +#ifdef WITH_HDF5 +#include +#include +#endif + +namespace ecell4 +{ + +class RandomNumberGenerator +{ +public: + + virtual ~RandomNumberGenerator() + { + ; + } + + virtual Real random() = 0; + virtual Real uniform(Real min, Real max) = 0; + virtual Integer uniform_int(Integer min, Integer max) = 0; + virtual Real gaussian(Real sigma, Real mean = 0.0) = 0; + virtual Integer binomial(Real p, Integer n) = 0; + virtual Real3 direction3d(Real length = 1.0) = 0; + + virtual void seed(Integer val) = 0; + virtual void seed() = 0; + +#ifdef WITH_HDF5 + virtual void save(H5::H5Location* root) const = 0; + virtual void load(const H5::H5Location& root) = 0; + virtual void save(const std::string& filename) const = 0; + virtual void load(const std::string& filename) = 0; +#else + void save(const std::string& filename) const + { + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); + } + + void load(const std::string& filename) + { + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); + } +#endif + +}; + +template +inline void shuffle(RandomNumberGenerator& rng, std::vector& cont) +{ + using std::swap; + typedef std::vector container_type; + for (typename container_type::size_type i(cont.size()); i > 0;) + { + --i; + typename container_type::size_type const j(rng.uniform_int(0, i)); + swap(cont[i], cont[j]); + } +} + +class GSLRandomNumberGenerator + : public RandomNumberGenerator +{ +public: + + typedef std::shared_ptr rng_handle; + +public: + + Real random(); + Real uniform(Real min, Real max); + Integer uniform_int(Integer min, Integer max); + Real gaussian(Real sigma, Real mean = 0.0); + Integer binomial(Real p, Integer n); + Real3 direction3d(Real length); + void seed(Integer val); + void seed(); + +#ifdef WITH_HDF5 + void save(H5::H5Location* root) const; + void load(const H5::H5Location& root); + void save(const std::string& filename) const; + void load(const std::string& filename); +#endif + + GSLRandomNumberGenerator() + : rng_(gsl_rng_alloc(gsl_rng_mt19937), &gsl_rng_free) + { + ; + } + + GSLRandomNumberGenerator(const Integer myseed) + : rng_(gsl_rng_alloc(gsl_rng_mt19937), &gsl_rng_free) + { + seed(myseed); + } + + GSLRandomNumberGenerator(const std::string& filename) + : rng_(gsl_rng_alloc(gsl_rng_mt19937), &gsl_rng_free) + { + load(filename); + } + + // GSLRandomNumberGenerator(rng_handle hdl) + // : rng_(hdl) + // { + // ; + // } + + // GSLRandomNumberGenerator(gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937)) + // : rng_(rng, &gsl_rng_free) + // { + // ; + // } + +protected: + + rng_handle rng_; +}; + +} // ecell4 + +#endif /* ECELL4_RANDOM_NUMBER_GENERATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Mesh.cpp",".cpp","5527","151","#include +#include ""Mesh.hpp"" +#include ""exceptions.hpp"" + +namespace ecell4 +{ + +MeshSurface::MeshSurface(const std::string filename, const Real3& edge_lengths) + : filename_(filename), edge_lengths_(edge_lengths) +{ +#ifdef HAVE_VTK + { + reader_ = vtkSmartPointer::New(); + reader_->SetFileName(filename_.c_str()); + reader_->Update(); + // tree_ = vtkSmartPointer::New(); + // tree_->SetDataSet(reader_->GetOutput()); + // tree_->BuildLocator(); + } + + { + Real bounds[6]; + reader_->GetOutput()->GetBounds(bounds); + + const Real xratio(edge_lengths_[0] / (bounds[1] - bounds[0])); + const Real yratio(edge_lengths_[1] / (bounds[3] - bounds[2])); + const Real zratio(edge_lengths_[2] / (bounds[5] - bounds[4])); + ratio_ = std::min(std::min(xratio, yratio), zratio); + shift_ = Real3(-bounds[0], -bounds[2], -bounds[4]); //XXX: align origin + } +#endif +} + +MeshSurface::MeshSurface(const MeshSurface& rhs) + : filename_(rhs.filename()), edge_lengths_(rhs.edge_lengths()) +{ +#ifdef HAVE_VTK + { + reader_ = vtkSmartPointer::New(); + reader_->SetFileName(filename_.c_str()); + reader_->Update(); + // tree_ = vtkSmartPointer::New(); + // tree_->SetDataSet(reader_->GetOutput()); + // tree_->BuildLocator(); + } + + { + Real bounds[6]; + reader_->GetOutput()->GetBounds(bounds); + + const Real xratio(edge_lengths_[0] / (bounds[1] - bounds[0])); + const Real yratio(edge_lengths_[1] / (bounds[3] - bounds[2])); + const Real zratio(edge_lengths_[2] / (bounds[5] - bounds[4])); + ratio_ = std::min(std::min(xratio, yratio), zratio); + shift_ = Real3(-bounds[0], -bounds[2], -bounds[4]); //XXX: align origin + } +#endif +} + +Real MeshSurface::is_inside(const Real3& pos) const +{ +#ifdef HAVE_VTK + double lineP0[3]; + lineP0[0] = pos[0] / ratio_ - shift_[0]; + lineP0[1] = pos[1] / ratio_ - shift_[1]; + lineP0[2] = pos[2] / ratio_ - shift_[2]; + vtkSmartPointer points = vtkSmartPointer::New(); + points->InsertNextPoint(lineP0); + + vtkSmartPointer pointsPolydata = vtkSmartPointer::New(); + pointsPolydata->SetPoints(points); + vtkSmartPointer selectEnclosedPoints + = vtkSmartPointer::New(); + selectEnclosedPoints->SetInput(pointsPolydata); + selectEnclosedPoints->SetSurface(reader_->GetOutput()); + selectEnclosedPoints->Update(); + return (selectEnclosedPoints->IsInside(0) ? 0.0 : std::numeric_limits::infinity()); + + // double lineP0[3]; + // lineP0[0] = pos[0] / ratio_ - shift_[0]; + // lineP0[1] = pos[1] / ratio_ - shift_[1]; + // lineP0[2] = pos[2] / ratio_ - shift_[2]; + // double lineP1[3]; + // lineP1[0] = 0.0 / ratio_ - shift_[0]; + // lineP1[1] = pos[1] / ratio_ - shift_[1]; + // lineP1[2] = pos[2] / ratio_ - shift_[2]; + // vtkSmartPointer intersectPoints = vtkSmartPointer::New(); + // tree_->IntersectWithLine(lineP0, lineP1, intersectPoints, NULL); + // return (intersectPoints->GetNumberOfPoints() % 2 == 1 ? 0.0 : inf); +#else + throw NotImplemented(""not implemented yet.""); +#endif +} + +Real3 MeshSurface::draw_position(std::shared_ptr& rng) const +{ +#ifdef HAVE_VTK + vtkPolyData* polydata = reader_->GetOutput(); + std::vector areas(polydata->GetNumberOfCells()); + for (vtkIdType i(0); i < polydata->GetNumberOfCells(); i++) + { + vtkCell* cell = polydata->GetCell(i); + vtkTriangle* triangle = dynamic_cast(cell); + double p0[3]; + double p1[3]; + double p2[3]; + triangle->GetPoints()->GetPoint(0, p0); + triangle->GetPoints()->GetPoint(1, p1); + triangle->GetPoints()->GetPoint(2, p2); + const double area = vtkTriangle::TriangleArea(p0, p1, p2); + // std::cout << ""p0: "" << p0[0] << "" "" << p0[1] << "" "" << p0[2] << std::endl; + // std::cout << ""p1: "" << p1[0] << "" "" << p1[1] << "" "" << p1[2] << std::endl; + // std::cout << ""p2: "" << p2[0] << "" "" << p2[1] << "" "" << p2[2] << std::endl; + // std::cout << ""area of triangle "" << i << "": "" << area << std::endl; + areas[i] = area; + } + const double rnd = rng->uniform(0.0, std::accumulate(areas.begin(), areas.end(), 0.0)); + double totarea = 0.0; + for (vtkIdType i(0); i < polydata->GetNumberOfCells(); i++) + { + totarea += areas[i]; + if (rnd < totarea) + { + vtkCell* cell = polydata->GetCell(i); + vtkTriangle* triangle = dynamic_cast(cell); + double p0[3]; + double p1[3]; + double p2[3]; + triangle->GetPoints()->GetPoint(0, p0); + triangle->GetPoints()->GetPoint(1, p1); + triangle->GetPoints()->GetPoint(2, p2); + const Real3 P0(p0[0], p0[1], p0[2]); + const Real3 P1(p1[0], p1[1], p1[2]); + const Real3 P2(p2[0], p2[1], p2[2]); + const Real p(rng->uniform(0.0, 1.0)), q(rng->uniform(0.0, 1.0 - p)); + return (((P1 - P0) * p + (P2 - P0) * q + P0) + shift_) * ratio_; + } + } + throw IllegalState(""Never reach here.""); +#else + throw NotImplemented(""not implemented yet.""); +#endif +} + +bool MeshSurface::test_AABB(const Real3& l, const Real3& u) const +{ + throw NotImplemented(""not implemented yet.""); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/STLFileIO.cpp",".cpp","9274","325","#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +struct endsolid_appeared{}; + +static Real3 read_ascii_stl_vertex(const std::string& line) +{ + std::istringstream iss(line); + + std::string prefix; + iss >> prefix; + if(prefix != ""vertex"") + { + throw std::runtime_error(""syntax error: missing vertex line""); + } + + Real x, y, z; + iss >> x >> y >> z; + return Real3(x, y, z); +} + +static Real3 read_ascii_stl_normal(const std::string& line) +{ + std::istringstream iss(line); + + std::string facet, normal; + iss >> facet >> normal; + if(facet != ""facet"" || normal != ""normal"") + { + throw std::runtime_error(""syntax error: missing `facet normal`""); + } + + Real x, y, z; + iss >> x >> y >> z; + return Real3(x, y, z); +} + +static Triangle read_ascii_stl_triangle(std::ifstream& ifs) +{ + std::array vs; + bool normal_read = false; + std::size_t vertex_index = 0; + while(!ifs.eof()) + { + std::string line; + std::getline(ifs, line); + std::istringstream iss(line); + std::string prefix; + iss >> prefix; + + if(prefix == ""facet"") + { + if(normal_read) + { + throw std::runtime_error(""syntax error: duplicated `normal`""); + } + normal_read = true; + // XXX ignore normal written in the file + read_ascii_stl_normal(line); + } + else if(prefix == ""outer"") + { + ; // outer loop. ignore. + } + else if(prefix == ""vertex"") + { + if(vertex_index > 2) + { + throw NotSupported(""STL contains more than 3 vertices""); + } + vs.at(vertex_index) = read_ascii_stl_vertex(line); + ++vertex_index; + } + else if(prefix == ""endloop"") + { + ; + } + else if(prefix == ""endfacet"") + { + return Triangle(vs); + } + else if(prefix == ""endsolid"") + { + throw endsolid_appeared(); + } + else + { + // comment line? do nothing. + } + ifs.peek(); + } + throw std::runtime_error(""invalid syntax""); +} + +static std::vector read_ascii_stl(const std::string& filename) +{ + std::ifstream ifs(filename.c_str()); + if(!ifs.good()) + { + throw std::runtime_error(""file open error: "" + filename); + } + + while(!ifs.eof()) + { + std::string line; + std::getline(ifs, line); + std::istringstream iss(line); + std::string prefix; + iss >> prefix; + if(prefix == ""solid"") + { + break; + } + ifs.peek(); + } + if(ifs.eof()) + { + throw std::runtime_error(""could not find solid line""); + } + + std::vector retval; + while(!ifs.eof()) + { + try + { + retval.push_back(read_ascii_stl_triangle(ifs)); + } + catch(endsolid_appeared& esl) + { + break; + } + ifs.peek(); + } + return retval; +} + +static Real3 read_binary_stl_vector(std::ifstream& ifs) +{ + float x, y, z; + ifs.read(reinterpret_cast(&x), sizeof(float)); + ifs.read(reinterpret_cast(&y), sizeof(float)); + ifs.read(reinterpret_cast(&z), sizeof(float)); + return Real3(x, y, z); +} + +static Triangle read_binary_stl_triangle(std::ifstream& ifs) +{ + // ignore normal vector written in the file + read_binary_stl_vector(ifs); + std::array vs; + vs[0] = read_binary_stl_vector(ifs); + vs[1] = read_binary_stl_vector(ifs); + vs[2] = read_binary_stl_vector(ifs); + ifs.ignore(2); + return Triangle(vs); +} + +static std::vector +read_binary_stl(const std::string& filename) +{ + std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary); + if(!ifs.good()) + { + throw std::runtime_error(""file open error: "" + filename); + } + + ifs.seekg(0, ifs.end); + const std::size_t size_of_file = ifs.tellg(); + ifs.seekg(0, ifs.beg); + + char ch_header[81]; + ifs.read(ch_header, 80); + ch_header[80] = '\0'; + + std::uint32_t num_triangle = 0; + ifs.read(reinterpret_cast(&num_triangle), 4); + + if(50 * num_triangle + 84 != size_of_file) + { + throw std::runtime_error((boost::format(""ecell4::read_binary_stl: "" + ""invalid filesize: %1% != %2% triagnles * 50 + header(84)"") % + size_of_file % num_triangle).str()); + } + + std::vector retval(num_triangle); + for(std::uint32_t i=0; i < num_triangle; ++i) + { + retval.at(i) = read_binary_stl_triangle(ifs); + } + return retval; +} + +std::vector +read_stl_format(const std::string& filename, const STLFormat kind) +{ + switch(kind) + { + case STLFormat::Ascii: return read_ascii_stl(filename); + case STLFormat::Binary: return read_binary_stl(filename); + default: throw std::invalid_argument(""read_stl_format: unknown format""); + } +} + +static void write_binary_stl( + const std::string& filename, const std::vector& tri) +{ + std::ofstream ofs(filename.c_str(), std::ios::out | std::ios::binary); + if(!ofs.good()) + { + throw std::runtime_error( + ""ecell4::write_stl_format: file open error: "" + filename); + } + + const std::string header(""this file is generated by ecell4::write_"" + ""stl_format. ""); + assert(header.size() == 80); + ofs.write(header.c_str(), 80); + + const std::uint32_t num_triangle = tri.size(); + ofs.write(reinterpret_cast(&num_triangle), 4); + + for(typename std::vector::const_iterator + iter = tri.begin(); iter != tri.end(); ++iter) + { + const float nx(iter->normal()[0]); + const float ny(iter->normal()[1]); + const float nz(iter->normal()[2]); + const float v0x(iter->vertex_at(0)[0]); + const float v0y(iter->vertex_at(0)[1]); + const float v0z(iter->vertex_at(0)[2]); + const float v1x(iter->vertex_at(1)[0]); + const float v1y(iter->vertex_at(1)[1]); + const float v1z(iter->vertex_at(1)[2]); + const float v2x(iter->vertex_at(2)[0]); + const float v2y(iter->vertex_at(2)[1]); + const float v2z(iter->vertex_at(2)[2]); + + ofs.write(reinterpret_cast(&nx), 4); + ofs.write(reinterpret_cast(&ny), 4); + ofs.write(reinterpret_cast(&nz), 4); + ofs.write(reinterpret_cast(&v0x), 4); + ofs.write(reinterpret_cast(&v0y), 4); + ofs.write(reinterpret_cast(&v0z), 4); + ofs.write(reinterpret_cast(&v1x), 4); + ofs.write(reinterpret_cast(&v1y), 4); + ofs.write(reinterpret_cast(&v1z), 4); + ofs.write(reinterpret_cast(&v2x), 4); + ofs.write(reinterpret_cast(&v2y), 4); + ofs.write(reinterpret_cast(&v2z), 4); + + const std::uint16_t attr(0); + ofs.write(reinterpret_cast(&attr), 2); + } + ofs.close(); + return; +} + +static void write_ascii_stl( + const std::string& filename, const std::vector& tri) +{ + std::ofstream ofs(filename.c_str()); + if(!ofs.good()) + { + throw std::runtime_error( + ""ecell4::write_stl_format: file open error: "" + filename); + } + + ofs << ""solid ecell4\n""; + ofs << std::setprecision(16); + for(typename std::vector::const_iterator + iter = tri.begin(); iter != tri.end(); ++iter) + { + const Real3 n = iter->normal(); + const Real3& v0 = iter->vertex_at(0); + const Real3& v1 = iter->vertex_at(1); + const Real3& v2 = iter->vertex_at(2); + + ofs << ""facet normal "" << n[0] << ' ' << n[1] << ' ' << n[1] << '\n'; + ofs << "" outer loop\n""; + ofs << "" vertex "" << v0[0] << ' ' << v0[1] << ' ' << v0[2] << '\n'; + ofs << "" vertex "" << v1[0] << ' ' << v1[1] << ' ' << v1[2] << '\n'; + ofs << "" vertex "" << v2[0] << ' ' << v2[1] << ' ' << v2[2] << '\n'; + ofs << "" endloop\n""; + ofs << ""endfacet\n""; + } + ofs << ""endsolid ecell4\n""; + ofs.close(); + return; +} + +void write_stl_format(const std::string& filename, const STLFormat kind, + const std::vector& tri) +{ + switch(kind) + { + case STLFormat::Ascii: return write_ascii_stl (filename, tri); + case STLFormat::Binary: return write_binary_stl(filename, tri); + default: throw std::invalid_argument(""write_stl_format: unknown format""); + } +} + +// ============================================================================= + +Polygon read_polygon(const std::string& fname, const STLFormat fmt, + const Real3& edge_lengths) +{ + return Polygon(edge_lengths, read_stl_format(fname, fmt)); +} +void write_polygon(const std::string& filename, const STLFormat fmt, + const Polygon& polygon) +{ + write_stl_format(filename, fmt, polygon.triangles()); + return; +} + +}// ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/PolygonHDF5Writer.cpp",".cpp","5435","143","#include +#include + +namespace ecell4 +{ + +struct PolygonHDF5Traits +{ + struct h5_triangle_struct { + double p1x; + double p1y; + double p1z; + double p2x; + double p2y; + double p2z; + double p3x; + double p3y; + double p3z; + }; + + static H5::CompType get_triangle_comp_type() + { + H5::CompType h5_triangle_comp_type(sizeof(h5_triangle_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(h5_triangle_comp_type.getId(), #member,\ + HOFFSET(h5_triangle_struct, member), type.getId()) + INSERT_MEMBER(p1x, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p1y, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p1z, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p2x, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p2y, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p2z, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p3x, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p3y, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(p3z, H5::PredType::NATIVE_DOUBLE); +#undef INSERT_MEMBER + return h5_triangle_comp_type; + } +}; + +void save_polygon_hdf5(const Polygon& p, H5::Group* root) +{ + using traits_type = PolygonHDF5Traits; + using h5_triangle_struct = traits_type::h5_triangle_struct; + + // ---------------------------------------------------------------------- + // convert face data into the simpler type, h5_triangle_structs + + const auto triangles = p.triangles(); + const unsigned int num_triangles = triangles.size(); + + std::unique_ptr + h5_triangle_table(new h5_triangle_struct[num_triangles]); + for(std::size_t i=0; i dataset(new H5::DataSet(root->createDataSet( + ""triangles"", traits_type::get_triangle_comp_type(), dataspace))); + dataset->write(h5_triangle_table.get(), dataset->getDataType()); + + // ---------------------------------------------------------------------- + // save edge lengths + const Real3 edge_lengths = p.edge_lengths(); + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + H5::Attribute attr_lengths(root->createAttribute( + ""edge_lengths"", lengths_type, H5::DataSpace(H5S_SCALAR))); + double lengths[] = {edge_lengths[0], edge_lengths[1], edge_lengths[2]}; + attr_lengths.write(lengths_type, lengths); + + // ---------------------------------------------------------------------- + // Since `Polygon` does not allow to remove/insert new triangle, the + // triangles saved here should have been assigned all at once. + // To make Identifier consistent, we need to call `polygon.assign` while + // loading. If we did that, we don't need to save the corresponding IDs + // because polygon->assign() function assigns the same IDs, in the same order. + + return; +} + +void load_polygon_hdf5(const H5::Group& root, Polygon* p) +{ + using traits_type = PolygonHDF5Traits; + using h5_triangle_struct = traits_type::h5_triangle_struct; + + // ---------------------------------------------------------------------- + // load edge_lengths before assigning triangles + Real3 edge_lengths; + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + root.openAttribute(""edge_lengths"").read(lengths_type, &edge_lengths); + + p->reset(edge_lengths); + + H5::DataSet triangle_dset(root.openDataSet(""triangles"")); + const unsigned int num_triangles( + triangle_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr h5_triangle_table( + new h5_triangle_struct[num_triangles]); + + triangle_dset.read(h5_triangle_table.get(), + traits_type::get_triangle_comp_type()); + triangle_dset.close(); + + std::vector triangles; + triangles.reserve(num_triangles); + for(std::size_t i=0; iassign(triangles); + return; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/StructureType.hpp",".hpp","1084","56","#ifndef ECELL4_STRUCTURE_TYPE_HPP +#define ECELL4_STRUCTURE_TYPE_HPP + +#include ""VoxelPool.hpp"" + +namespace ecell4 +{ + +class StructureType : public VoxelPool +{ +private: + typedef VoxelPool base_type; + +public: + StructureType(const Species &species, std::weak_ptr location) + : base_type(species, location), size_(0) + { + ; + } + + virtual ~StructureType() { ; } + + virtual voxel_type_type const voxel_type() const { return STRUCTURE; } + + const Integer size() const { return size_; } + + void add_voxel(const coordinate_id_pair_type &info) + { + if (info.pid != ParticleID()) + { + throw NotSupported(""No ParticleID is allowed.""); + } + + ++size_; + } + + coordinate_id_pair_type pop(const coordinate_type &coord) + { + --size_; + return coordinate_id_pair_type(ParticleID(), coord); + } + + bool remove_voxel_if_exists(const coordinate_type &coord) + { + --size_; + return true; + } + +private: + Integer size_; +}; + +} // namespace ecell4 + +#endif /* ECELL4_STRUCTURE_TYPE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Quantity.hpp",".hpp","1104","57","#ifndef ECELL4_QUANTITY_HPP +#define ECELL4_QUANTITY_HPP + +#include +#include +#include + +#include ""types.hpp"" + + +namespace ecell4 +{ + +template +struct Quantity +{ + typedef T magnitude_type; + typedef std::string units_type; + + magnitude_type magnitude; + units_type units; + + Quantity() + : magnitude(), units("""") + { + ; + } + + Quantity(const magnitude_type& m, const units_type& u="""") + : magnitude(m), units(u) + { + ; + } + + bool operator==(const Quantity& another) const + { + return (magnitude == another.magnitude && units == another.units); + } + + bool operator!=(const Quantity& another) const + { + return (magnitude != another.magnitude || units != another.units); + } +}; + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& strm, const Quantity& value) +{ + strm << value.magnitude << "" "" << value.units; + return strm; +} + +} // ecell4 + +#endif /* ECELL4_QUANTITY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Simulator.hpp",".hpp","1383","84","#ifndef ECELL4_SIMULATOR_HPP +#define ECELL4_SIMULATOR_HPP + +#include +#include ""types.hpp"" +#include ""ReactionRule.hpp"" + + +namespace ecell4 +{ + +class Simulator +{ +public: + + virtual ~Simulator() + { + ; // do nothing + } + + // SimulatorTraits + + /** + * initialize + */ + virtual void initialize() = 0; + + /** + * get current time. + * @return time Real + */ + virtual Real t() const = 0; + + /** + * get step interval. + * @return dt Real + */ + virtual Real dt() const = 0; + + /** + * set step interval. + */ + virtual void set_dt(const Real& dt) = 0; + + /** + * get the number of steps. + * @return the number of steps Integer + */ + virtual Integer num_steps() const = 0; + + /** + * step. + */ + virtual void step() = 0; + + /** + * step and return true if the next time is less than upto. + * if not, step till upto and return false. + * @return if the simulator does not rearch upto + */ + virtual bool step(const Real& upto) = 0; + + /** + * get next time (t + dt). + * @return next time Real + */ + inline Real next_time() const + { + return t() + dt(); + } + + /** + * @return if any reaction occurs at the last step or not + */ + virtual bool check_reaction() const + { + return false; + } +}; + +} + +#endif /* ECELL4_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Mesh.hpp",".hpp","1686","81","#ifndef ECELL4_MESH_HPP +#define ECELL4_MESH_HPP + +#include +#include ""Shape.hpp"" + +#ifdef HAVE_VTK +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace ecell4 +{ + +struct MeshSurface + : public Shape +{ +public: + + MeshSurface(const std::string filename, const Real3& edge_lengths); + MeshSurface(const MeshSurface& rhs); + + std::string filename() const + { + return filename_; + } + + Real3 edge_lengths() const + { + return edge_lengths_; + } + + virtual dimension_kind dimension() const + { + return TWO; + } + + virtual Real is_inside(const Real3& pos) const; + virtual Real3 draw_position( + std::shared_ptr& rng) const; + virtual bool test_AABB(const Real3& l, const Real3& u) const; + +#ifdef HAVE_VTK + virtual void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + double bounds[6]; + reader_->GetOutput()->GetBounds(bounds); + + const Real xlim(ratio_ * (bounds[1] - bounds[0])); + const Real ylim(ratio_ * (bounds[3] - bounds[2])); + const Real zlim(ratio_ * (bounds[5] - bounds[4])); + + lower = Real3(0.0, 0.0, 0.0); + upper = Real3(xlim, ylim, zlim); + } +#endif + +protected: + + std::string filename_; + Real3 edge_lengths_; + Real ratio_; + Real3 shift_; + +#ifdef HAVE_VTK + vtkSmartPointer reader_; + // vtkSmartPointer tree_; +#endif +}; + +} // ecell4 + +#endif /* ECELL4_MESH_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Segment.hpp",".hpp","1521","66","#ifndef ECELL4_CORE_SEGMENT +#define ECELL4_CORE_SEGMENT +#include +#include + +namespace ecell4 +{ + +struct Segment + : public Shape +{ +public: + + /** for epdp + */ + typedef Real3 position_type; + typedef position_type::value_type length_type; + typedef position_type::value_type value_type; + +public: + + Segment(){} + Segment(const Real3& start, const Real3& stop): start_(start), stop_(stop){} + Segment(const Segment& rhs) : start_(rhs.start_), stop_(rhs.stop_){} + + Real3 draw_position(std::shared_ptr& rng) const + { + const Real r = rng->random(); + return start_ * r + stop_ * (1. - r); + } + Real is_inside(const Real3& coord) const + { + throw NotImplemented(""Segment::is_inside""); + } + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Segment::is_inside""); + } + + Real3 const& start() const {return start_;} + Real3& start() {return start_;} + Real3 const& stop() const {return stop_;} + Real3& stop() {return stop_;} + + dimension_kind dimension() const + { + return ONE; + } + +protected: + + Real3 start_; + Real3 stop_; +}; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const Segment& sgm) +{ + os << ""Segment("" << sgm.start() << "", "" << sgm.stop() << ')'; + return os; +} + +} // ecell4 +#endif// ECELL4_CORE_SEGMENT +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/LatticeSpaceVectorImpl.hpp",".hpp","3689","132","#ifndef ECELL4_LATTICE_SPACE_VECTOR_IMPL_HPP +#define ECELL4_LATTICE_SPACE_VECTOR_IMPL_HPP + +#include ""HCPLatticeSpace.hpp"" + +namespace ecell4 +{ + +class LatticeSpaceVectorImpl : public HCPLatticeSpace +{ +public: + typedef HCPLatticeSpace base_type; + typedef std::vector> voxel_container; + +public: + LatticeSpaceVectorImpl(const Real3 &edge_lengths, const Real &voxel_radius, + const bool is_periodic = true); + ~LatticeSpaceVectorImpl(); + + /* + * Space APIs + * + * using ParticleID, Species and Posision3 + */ + + Integer num_species() const; + + bool remove_voxel(const ParticleID &pid); + bool remove_voxel(const coordinate_type &coord); + + bool update_structure(const Particle &p); + + /* + * for Simulator + * + * using Species and coordinate_type + */ + std::vector list_voxels() const; + std::vector list_voxels(const Species &sp) const; + std::vector list_voxels_exact(const Species &sp) const; + + bool update_voxel(const ParticleID &pid, const Species &species, + const coordinate_type coordinate); + bool add_voxel(const Species &species, const ParticleID &pid, + const coordinate_type &coord); + + bool add_voxels(const Species &species, + std::vector> voxels); + + const Species &find_species(std::string name) const; + std::vector list_coords(const Species &sp) const; + std::vector list_coords_exact(const Species &sp) const; + + std::shared_ptr + get_voxel_pool_at(const coordinate_type &coord) const + { + return voxels_.at(coord); + } + + bool move(const coordinate_type &src, const coordinate_type &dest, + const std::size_t candidate = 0); + bool can_move(const coordinate_type &src, + const coordinate_type &dest) const; + + coordinate_type get_neighbor(const coordinate_type &coord, + const Integer &nrand) const + { + coordinate_type const dest = get_neighbor_(coord, nrand); + + if (voxels_.at(dest) != periodic_) + { + return dest; + } + else + { + return periodic_transpose(dest); + } + } + + bool is_periodic() const { return is_periodic_; } + +#ifdef WITH_HDF5 + /* + * HDF5 Save + */ + void save_hdf5(H5::Group *root) const + { + save_lattice_space(*this, root, ""LatticeSpaceVectorImpl""); + } + + void load_hdf5(const H5::Group &root) { load_lattice_space(root, this); } +#endif + + void reset(const Real3 &edge_lengths, const Real &voxel_radius, + const bool is_periodic) + { + base_type::reset(edge_lengths, voxel_radius, is_periodic); + + is_periodic_ = is_periodic; + initialize_voxels(is_periodic_); + } + +protected: + coordinate_type apply_boundary_(const coordinate_type &coord) const + { + return periodic_transpose(coord); + } + + void initialize_voxels(const bool is_periodic); + + std::pair move_(coordinate_type from, + coordinate_type to, + const std::size_t candidate = 0); + + std::pair move_(coordinate_id_pair_type &info, + coordinate_type to); + + coordinate_type get_coord(const ParticleID &pid) const; + +protected: + bool is_periodic_; + + voxel_container voxels_; + + std::shared_ptr border_; + std::shared_ptr periodic_; +}; + +} // namespace ecell4 + +#endif +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Space.hpp",".hpp","262","22","#ifndef ECELL4_SPACE_HPP +#define ECELL4_SPACE_HPP + +namespace ecell4 +{ + +struct Space +{ + typedef enum + { + ELSE, + PARTICLE, + LATTICE, + COMPARTMENT, + SUBVOLUME + } space_kind; +}; + +} // ecell4 + +#endif /* ECELL4_SPACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/functions.hpp",".hpp","2044","117","#ifndef ECELL4_FUNCTIONS_HPP +#define ECELL4_FUNCTIONS_HPP + +#include +#include + +#include + +#include ""types.hpp"" + +#include +#include + +#ifndef WIN32_MSC +#include +#include +#else +#include +#include +#endif + +#include +#include + + +namespace ecell4 +{ + +inline int64_t modulo(const int64_t& p1, const int64_t& p2) +{ + int64_t r = p1 % p2; + if (r != 0 && (r > 0) == (p2 < 0)) + { + r += p2; + } + return r; +} + +inline double modulo(const double& p1, const double& p2) +{ + double r = std::fmod(p1, p2); + if (r != 0 && (r > 0) == (p2 < 0)) + { + r += p2; + } + return r; +} + +inline int64_t abs(const int64_t& x) +{ + return (x > 0 ? x : -x); +} + +inline double abs(const double& x) +{ + return std::fabs(x); +} + +#ifndef WIN32_MSC +inline double pow_2(const double x) +{ + return gsl_pow_2(x); +} + +inline double pow_3(const double x) +{ + return gsl_pow_3(x); +} + +inline double cbrt(const double x) +{ + return ::cbrt(x); +} +#else +inline double pow_2(const double x) +{ + return x * x; +} + +inline double pow_3(const double x) +{ + return x * x * x; +} + +inline double cbrt(const double x) +{ + return pow(x, 1.0 / 3.0); +} +#endif + +/** + * Return if the root path of the given filename exists or not. + * boost::filesystem::is_directory might be better + * though it requires building. + */ +inline bool is_directory(const std::string& filename) +{ +#ifndef WIN32_MSC + struct stat buf; + const int ret = stat(dirname(strdup(filename.c_str())), &buf); + return (ret == 0); +#else + char drive[_MAX_DRIVE + 1], dir[_MAX_DIR + 1], path_dir[_MAX_PATH + 1], full[_MAX_PATH]; + // struct _stat buf; + _fullpath(full, filename.c_str(), _MAX_PATH); + _splitpath(full, drive, dir, NULL, NULL); + _makepath(path_dir, drive, dir, NULL, NULL); + // const int ret = _stat(path_dir, &buf); + const int ret = _access(path_dir, 0); + return (ret == 0); +#endif +} + +} + +#endif /* ECELL4_FUNCTIONS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpaceRTreeImpl.hpp",".hpp","10229","308","#ifndef ECELL4_PARTICLE_SPACE_RTREE_IMPL_HPP +#define ECELL4_PARTICLE_SPACE_RTREE_IMPL_HPP + +#include +#include +#include +#include +#include +#include +#include + +#ifdef WITH_HDF5 +#include +#endif + +#include + +namespace ecell4 +{ + +class ParticleSpaceRTreeImpl + : public ParticleSpace +{ +public: + struct ParticleAABBGetter + { + AABB operator()(const Particle& p, const Real margin) const noexcept + { + const Real3 radius(p.radius() + p.D() * margin, + p.radius() + p.D() * margin, + p.radius() + p.D() * margin); + return AABB(p.position() - radius, p.position() + radius); + } + }; + + using base_type = ParticleSpace; + using rtree_type = PeriodicRTree; + using box_type = typename rtree_type::box_type; + using value_type = typename rtree_type::value_type; + using key_to_value_map_type = typename rtree_type::key_to_value_map_type; + using particle_container_type = typename rtree_type::container_type; + using iterator = typename rtree_type::iterator; + using const_iterator = typename rtree_type::const_iterator; + + static_assert(std::is_same>::value, """"); + static_assert(std::is_same::value, """"); + + // species support + using particle_id_set = std::set; + using per_species_particle_id_set = + std::unordered_map; + +public: + + // the default value of margin should be tuned later. + explicit ParticleSpaceRTreeImpl(const Real3& edge_lengths, + const Real margin = 0.1) + : base_type(), rtree_(edge_lengths, margin) + {} + + void reset(const Real3& edge_lengths); + + // inherit from Space + + virtual Integer num_species() const + { + return particle_pool_.size(); + } + + virtual bool has_species(const Species& sp) const + { + return (particle_pool_.count(sp.serial()) != 0); + } + + // inherit from ParticleSpace + + const Real3& edge_lengths() const override + { + return rtree_.edge_lengths(); + } + + const particle_container_type& particles() const override + { + return rtree_.list_objects(); + } + + // ParticleSpace has the default list_species implementation. + // But it uses particles() member method that cannot be implemented with + // PeriodicRTree. So it overwrites the default implementation. + std::vector list_species() const override; + + std::pair get_particle(const ParticleID& pid) const override + { + if(!rtree_.has(pid)) + { + throw_exception(""ParticleSpaceRTreeImpl::get_particle: "" + ""No such particle ("", pid, "").""); + } + return rtree_.get(pid); + } + + // returns true if it adds a new particle + bool update_particle(const ParticleID& pid, const Particle& newp) override + { + if(rtree_.has(pid)) + { + const auto& oldp = rtree_.get(pid).second; + if(oldp.species() != newp.species()) + { + particle_pool_[oldp.species_serial()].erase (pid); + particle_pool_[newp.species_serial()].insert(pid); + } + // if species does not change, then we don't need to do anything. + } + else + { + // if `newp` is completely new, we need to insert it to the pool. + particle_pool_[newp.species_serial()].insert(pid); + } + const auto retval = rtree_.update(pid, newp); + assert(rtree_.diagnosis()); + assert(this->diagnosis()); + return retval; + } + bool has_particle(const ParticleID& pid) const override + { + return rtree_.has(pid); + } + void remove_particle(const ParticleID& pid) override + { + if(!rtree_.has(pid)) + { + throw_exception(""ParticleSpaceRTreeImpl::remove_particle:"" + "" No such particle ("", pid, "").""); + } + const auto& p = rtree_.get(pid).second; + particle_pool_[p.species_serial()].erase(pid); + rtree_.erase(pid, p); + return; + } + + Integer num_particles() const override + { + return rtree_.size(); + } + Integer num_particles (const Species& sp) const override; + Integer num_particles_exact(const Species& sp) const override; + Integer num_molecules (const Species& sp) const override; + Integer num_molecules_exact(const Species& sp) const override; + + std::vector > + list_particles() const override + { + return rtree_.list_objects(); + } + std::vector > + list_particles(const Species& sp) const override; + std::vector > + list_particles_exact(const Species& sp) const override; + + virtual void save(const std::string& filename) const + { + throw NotImplemented( + ""save(const std::string) is not supported by this space class""); + } + +#ifdef WITH_HDF5 + void save_hdf5(H5::Group* root) const override + { + save_particle_space(*this, root); + } + + void load_hdf5(const H5::Group& root) override + { + load_particle_space(root, this); + } +#endif + + std::vector, Real>> + list_particles_within_radius(const Real3& pos, const Real& radius) const override; + + std::vector, Real>> + list_particles_within_radius(const Real3& pos, const Real& radius, + const ParticleID& ignore) const override; + + std::vector, Real>> + list_particles_within_radius(const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const override; + + bool diagnosis() const + { + bool is_ok = true; + const auto ps = this->list_particles(); + for(std::size_t i=0; i+1distance_sq(pi.position(), pj.position()); + const auto dist = std::sqrt(d2) - pi.radius() - pj.radius(); + + if(dist < 0.0) + { + std::cerr << ""particle "" << ps.at(i).first; + std::cerr << "" and "" << ps.at(j).first; + std::cerr << "" collide with each other"" << std::endl; + is_ok = false; + } + } + } + return is_ok; + } + +protected: + + template + void query_impl(Query&& q, OutputIterator out) const + { + rtree_.query(std::forward(q), out); + return ; + } + + // ------------------------------------------------------------------------ + // query objects + + template + struct IntersectionQuery + { + Real3 center; + Real radius; + Filter ignores; + + IntersectionQuery(const Real3& c, const Real r, Filter f) noexcept + : center(c), radius(r), ignores(std::move(f)) + {} + IntersectionQuery(const IntersectionQuery&) = default; + IntersectionQuery(IntersectionQuery&&) = default; + IntersectionQuery& operator=(const IntersectionQuery&) = default; + IntersectionQuery& operator=(IntersectionQuery&&) = default; + ~IntersectionQuery() = default; + + // If it does not matches, return boost::none. + // If it matches, return pairof(pidp, distance). + boost::optional> + operator()(const value_type& pidp, const PeriodicBoundary& pbc) const noexcept + { + if(ignores(pidp)){return boost::none;} + + // use the same algorithm as the ParticleSpaceVectorImpl. + const auto rhs = pbc.periodic_transpose(pidp.second.position(), + this->center); + const auto dist = length(this->center - rhs) - pidp.second.radius(); + if(dist <= this->radius) + { + return std::make_pair(pidp, dist); + } + return boost::none; + } + + bool operator()(const AABB& box, const PeriodicBoundary& pbc) const noexcept + { + return this->distance_sq(box, this->center, pbc) <= + this->radius * this->radius; + } + + // ------------------------------------------------------------------- + // AABB-sphere distance under the PBC + Real distance_sq(const AABB& box, Real3 pos, const PeriodicBoundary& pbc) const noexcept + { + pos = pbc.periodic_transpose(pos, (box.upper() + box.lower()) * 0.5); + + Real dist_sq = 0; + for(std::size_t i=0; i<3; ++i) + { + const auto v = pos[i]; + if(v < box.lower()[i]) + { + dist_sq += (v - box.lower()[i]) * (v - box.lower()[i]); + } + else if(box.upper()[i] < v) + { + dist_sq += (v - box.upper()[i]) * (v - box.upper()[i]); + } + } + return dist_sq; + } + }; + + template + static IntersectionQuery make_intersection_query( + const Real3& c, const Real r, Filter&& f) + { + return IntersectionQuery(c, r, std::forward(f)); + } + +protected: + + rtree_type rtree_; + per_species_particle_id_set particle_pool_; +}; + +}; // ecell4 + +#endif /* ECELL4_PARTICLE_SPACE_CELL_LIST_IMPL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ModelWrapper.hpp",".hpp","3736","130","#include ""Model.hpp"" + + +namespace ecell4 +{ + +class ModelWrapper +{ +public: + + typedef Model::species_container_type species_container_type; + typedef Model::reaction_rule_container_type reaction_rule_container_type; + +protected: + + typedef std::unordered_map + species_attribute_cache_type; + typedef std::map > + first_order_reaction_rules_map_type; + typedef std::map, + std::vector > + second_order_reaction_rules_map_type; + +public: + + ModelWrapper(const std::shared_ptr& m) + : model_(m), species_attribute_cache_(), // species_cache_(), + first_order_reaction_rules_map_(), second_order_reaction_rules_map_() + { + ; + } + + virtual ~ModelWrapper() + { + ; + } + + const std::shared_ptr& backend() const + { + return model_; + } + + void initialize() + { + // species_cache_.clear(); + species_attribute_cache_.clear(); + first_order_reaction_rules_map_.clear(); + second_order_reaction_rules_map_.clear(); + } + + Integer apply(const Species& pttrn, const Species& sp) + { + return model_->apply(pttrn, sp); + } + + std::vector apply( + const ReactionRule& rr, + const ReactionRule::reactant_container_type& reactants) + { + return model_->apply(rr, reactants); + } + + Species apply_species_attributes(const Species& sp) + { + species_attribute_cache_type::const_iterator + itr(species_attribute_cache_.find(sp.serial())); + if (itr != species_attribute_cache_.end()) + { + return (*itr).second; + } + + Species retval(model_->apply_species_attributes(sp)); + species_attribute_cache_[sp.serial()] = retval; + return retval; + } + + std::vector query_reaction_rules(const Species& sp) + { + first_order_reaction_rules_map_type::const_iterator + i(first_order_reaction_rules_map_.find(sp.serial())); + if (i != first_order_reaction_rules_map_.end()) + { + return (*i).second; + } + + std::vector retval(model_->query_reaction_rules(sp)); + first_order_reaction_rules_map_.insert(std::make_pair(sp.serial(), retval)); + return retval; + } + + std::vector query_reaction_rules( + const Species& sp1, const Species& sp2) + { + const std::pair + key(sp1.serial() < sp2.serial()? + std::make_pair(sp1.serial(), sp2.serial()): + std::make_pair(sp2.serial(), sp1.serial())); + second_order_reaction_rules_map_type::const_iterator + i(second_order_reaction_rules_map_.find(key)); + if (i != second_order_reaction_rules_map_.end()) + { + return (*i).second; + } + + std::vector retval(model_->query_reaction_rules(sp1, sp2)); + second_order_reaction_rules_map_.insert(std::make_pair(key, retval)); + return retval; + } + + // const std::vector list_species() + // { + // if (species_cache_.size() == 0) + // { + // species_cache_ = model_->list_species(); + // } + // return species_cache_; + // } + +protected: + + std::shared_ptr model_; + + // species_container_type species_cache_; + species_attribute_cache_type species_attribute_cache_; + first_order_reaction_rules_map_type first_order_reaction_rules_map_; + second_order_reaction_rules_map_type second_order_reaction_rules_map_; +}; + +} // ecell4 +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/LatticeSpaceVectorImpl.cpp",".cpp","14083","527","#include ""Context.hpp"" +#include ""LatticeSpaceVectorImpl.hpp"" +#include ""MoleculePool.hpp"" +#include ""StructureType.hpp"" +#include ""VacantType.hpp"" + +namespace ecell4 +{ + +typedef LatticeSpaceVectorImpl::coordinate_type coordinate_type; + +LatticeSpaceVectorImpl::LatticeSpaceVectorImpl(const Real3 &edge_lengths, + const Real &voxel_radius, + const bool is_periodic) + : base_type(edge_lengths, voxel_radius, is_periodic), + is_periodic_(is_periodic) +{ + border_ = std::shared_ptr( + new MoleculePool(Species(""Border"", voxel_radius_, 0), vacant_)); + periodic_ = std::shared_ptr( + new MoleculePool(Species(""Periodic"", voxel_radius, 0), vacant_)); + + initialize_voxels(is_periodic_); +} + +LatticeSpaceVectorImpl::~LatticeSpaceVectorImpl() {} + +void LatticeSpaceVectorImpl::initialize_voxels(const bool is_periodic) +{ + const coordinate_type voxel_size(col_size_ * row_size_ * layer_size_); + // std::cout << ""voxel_size = "" << voxel_size << std::endl; + + voxel_pools_.clear(); + molecule_pools_.clear(); + voxels_.clear(); + voxels_.reserve(voxel_size); + for (coordinate_type coord(0); coord < voxel_size; ++coord) + { + if (!is_inside(coord)) + { + if (is_periodic) + { + voxels_.push_back(periodic_); + periodic_->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + } + else + { + voxels_.push_back(border_); + border_->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + } + } + else + { + voxels_.push_back(vacant_); + vacant_->add_voxel(coordinate_id_pair_type(ParticleID(), coord)); + } + } +} + +Integer LatticeSpaceVectorImpl::num_species() const +{ + return voxel_pools_.size() + molecule_pools_.size(); +} + +bool LatticeSpaceVectorImpl::update_structure(const Particle &p) +{ + return update_voxel(ParticleID(), p.species(), + position2coordinate(p.position())); +} + +/* + * original methods + */ + +const Species &LatticeSpaceVectorImpl::find_species(std::string name) const +{ + for (const auto &pool : voxel_pools_) + { + if (pool.first.serial() == name) + { + return pool.first; + } + } + + for (const auto &pool : molecule_pools_) + { + if (pool.first.serial() == name) + { + return pool.first; + } + } + throw NotFound(name); +} + +std::vector +LatticeSpaceVectorImpl::list_coords_exact(const Species &sp) const +{ + std::vector retval; + + molecule_pool_map_type::const_iterator itr(molecule_pools_.find(sp)); + if (itr == molecule_pools_.end()) + { + return retval; + } + + const std::shared_ptr &vp((*itr).second); + + for (const auto &voxel : *vp) + { + retval.push_back(voxel.coordinate); + } + return retval; +} + +std::vector +LatticeSpaceVectorImpl::list_coords(const Species &sp) const +{ + std::vector retval; + for (const auto &pool : molecule_pools_) + { + if (!SpeciesExpressionMatcher(sp).match(pool.first)) + { + continue; + } + + const std::shared_ptr &vp(pool.second); + + for (const auto &voxel : *vp) + { + retval.push_back(voxel.coordinate); + } + } + return retval; +} + +std::vector LatticeSpaceVectorImpl::list_voxels() const +{ + std::vector retval; + + for (const auto &pool : molecule_pools_) + { + const std::shared_ptr &vp(pool.second); + const Species &sp(vp->species()); + + for (const auto &voxel : *vp) + { + retval.push_back(VoxelView(voxel.pid, sp, voxel.coordinate)); + } + } + + for (const auto &pool : voxel_pools_) + { + const std::shared_ptr &vp(pool.second); + const Species &sp(vp->species()); + + for (voxel_container::const_iterator i(voxels_.begin()); + i != voxels_.end(); ++i) + { + if (*i != vp) + { + continue; + } + + const coordinate_type coord(std::distance(voxels_.begin(), i)); + retval.push_back(VoxelView(ParticleID(), sp, coord)); + } + } + return retval; +} + +std::vector +LatticeSpaceVectorImpl::list_voxels_exact(const Species &sp) const +{ + std::vector retval; + + { + voxel_pool_map_type::const_iterator itr(voxel_pools_.find(sp)); + if (itr != voxel_pools_.end()) + { + const std::shared_ptr &vp((*itr).second); + for (voxel_container::const_iterator i(voxels_.begin()); + i != voxels_.end(); ++i) + { + if (*i != vp) + { + continue; + } + + const coordinate_type coord(std::distance(voxels_.begin(), i)); + retval.push_back(VoxelView(ParticleID(), sp, coord)); + } + return retval; + } + } + + { + molecule_pool_map_type::const_iterator itr(molecule_pools_.find(sp)); + if (itr != molecule_pools_.end()) + { + const std::shared_ptr &vp((*itr).second); + for (const auto &voxel : *vp) + { + retval.push_back(VoxelView(voxel.pid, sp, voxel.coordinate)); + } + return retval; + } + } + return retval; // an empty vector +} + +std::vector +LatticeSpaceVectorImpl::list_voxels(const Species &sp) const +{ + std::vector retval; + SpeciesExpressionMatcher sexp(sp); + + for (const auto &pool : voxel_pools_) + { + if (!sexp.match(pool.first)) + { + continue; + } + + const std::shared_ptr &vp(pool.second); + const Species &sp(vp->species()); + for (voxel_container::const_iterator i(voxels_.begin()); + i != voxels_.end(); ++i) + { + if (*i != vp) + { + continue; + } + + const coordinate_type coord(std::distance(voxels_.begin(), i)); + retval.push_back(VoxelView(ParticleID(), sp, coord)); + } + } + + for (const auto &pool : molecule_pools_) + { + if (!sexp.match(pool.first)) + { + continue; + } + + const std::shared_ptr &vp(pool.second); + const Species &sp(vp->species()); + for (const auto &voxel : *vp) + { + retval.push_back(VoxelView(voxel.pid, sp, voxel.coordinate)); + } + } + + return retval; +} + +/* + * Protected functions + */ + +coordinate_type LatticeSpaceVectorImpl::get_coord(const ParticleID &pid) const +{ + for (const auto &pool : molecule_pools_) + { + const std::shared_ptr &vp(pool.second); + for (const auto &voxel : *vp) + { + if (voxel.pid == pid) + { + return voxel.coordinate; + } + } + } + return -1; // XXX: a bit dirty way +} + +// bool LatticeSpaceVectorImpl::has_species_exact(const Species& sp) const +// { +// return spmap_.find(sp) != spmap_.end(); +// } + +bool LatticeSpaceVectorImpl::remove_voxel(const ParticleID &pid) +{ + for (const auto &pool : molecule_pools_) + { + const std::shared_ptr &vp(pool.second); + MoleculePool::const_iterator j(vp->find(pid)); + if (j != vp->end()) + { + const coordinate_type coord((*j).coordinate); + if (!vp->remove_voxel_if_exists(coord)) + { + return false; + } + + voxels_.at(coord) = vp->location(); + + vp->location()->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + return true; + } + } + return false; +} + +bool LatticeSpaceVectorImpl::remove_voxel(const coordinate_type &coord) +{ + std::shared_ptr vp(voxels_.at(coord)); + if (auto location_ptr = vp->location()) + { + if (vp->remove_voxel_if_exists(coord)) + { + voxels_.at(coord) = location_ptr; + location_ptr->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + return true; + } + } + return false; +} + +bool LatticeSpaceVectorImpl::move(const coordinate_type &src, + const coordinate_type &dest, + const std::size_t candidate) +{ + return move_(src, dest, candidate).second; +} + +bool LatticeSpaceVectorImpl::can_move(const coordinate_type &src, + const coordinate_type &dest) const +{ + if (src == dest) + return false; + + std::shared_ptr src_vp(voxels_.at(src)); + if (src_vp->is_vacant()) + return false; + + std::shared_ptr dest_vp(voxels_.at(dest)); + + if (dest_vp == border_) + return false; + + if (dest_vp == periodic_) + dest_vp = voxels_.at(apply_boundary_(dest)); + + return (dest_vp == src_vp->location()); +} + +std::pair +LatticeSpaceVectorImpl::move_(coordinate_type from, coordinate_type to, + const std::size_t candidate) +{ + if (from == to) + { + return std::pair(from, false); + } + + std::shared_ptr from_vp(voxels_.at(from)); + if (from_vp->is_vacant()) + { + return std::pair(from, true); + } + + std::shared_ptr to_vp(voxels_.at(to)); + + if (to_vp == border_) + { + return std::pair(from, false); + } + else if (to_vp == periodic_) + { + to = apply_boundary_(to); + to_vp = voxels_.at(to); + } + + if (to_vp != from_vp->location()) + { + return std::pair(to, false); + } + + from_vp->replace_voxel(from, to, candidate); + voxels_.at(from) = to_vp; + + to_vp->replace_voxel(to, from); + voxels_.at(to) = from_vp; + + return std::pair(to, true); +} + +std::pair +LatticeSpaceVectorImpl::move_(coordinate_id_pair_type &info, coordinate_type to) +{ + const coordinate_type from(info.coordinate); + if (from == to) + { + return std::pair(from, false); + } + + std::shared_ptr from_vp(voxels_.at(from)); + if (from_vp->is_vacant()) + { + return std::pair(from, true); + } + + std::shared_ptr to_vp(voxels_.at(to)); + + if (to_vp == border_) + { + return std::pair(from, false); + } + else if (to_vp == periodic_) + { + to = apply_boundary_(to); + to_vp = voxels_.at(to); + } + + if (to_vp != from_vp->location()) + { + return std::pair(to, false); + } + + info.coordinate = to; + voxels_.at(from) = to_vp; + + // to_vp->replace_voxel(to, coordinate_id_pair_type(ParticleID(), from)); + to_vp->replace_voxel(to, from); + voxels_.at(to) = from_vp; + + return std::pair(to, true); +} + +/* + * Change the Species and coordinate of a Voxel with ParticleID, pid, to + * species and coordinate respectively and return false. + * If no Voxel with pid is found, create a new Voxel at + * coordiante() and return true. + */ +bool LatticeSpaceVectorImpl::update_voxel(const ParticleID &pid, + const Species &species, + const coordinate_type to_coord) +{ + if (!is_in_range(to_coord)) + { + throw NotSupported(""Out of bounds""); + } + + std::shared_ptr new_vp( + find_voxel_pool(species)); // XXX: need MoleculeInfo + std::shared_ptr dest_vp(get_voxel_pool_at(to_coord)); + + if (dest_vp != new_vp->location()) + { + throw NotSupported(""Mismatch in the location. Failed to place '"" + + new_vp->species().serial() + ""' to '"" + + dest_vp->species().serial() + ""'.""); + } + + const coordinate_type from_coord(pid != ParticleID() ? get_coord(pid) : -1); + if (from_coord != -1) + { + // move + voxels_.at(from_coord)->remove_voxel_if_exists(from_coord); + + // XXX: use location? + dest_vp->replace_voxel(to_coord, from_coord); + voxels_.at(from_coord) = dest_vp; + + new_vp->add_voxel(coordinate_id_pair_type(pid, to_coord)); + voxels_.at(to_coord) = new_vp; + return false; + } + + // new + dest_vp->remove_voxel_if_exists(to_coord); + + new_vp->add_voxel(coordinate_id_pair_type(pid, to_coord)); + voxels_.at(to_coord) = new_vp; + return true; +} + +bool LatticeSpaceVectorImpl::add_voxel(const Species &sp, const ParticleID &pid, + const coordinate_type &coordinate) +{ + std::shared_ptr vpool(find_voxel_pool(sp)); + std::shared_ptr location(get_voxel_pool_at(coordinate)); + + if (vpool->location() != location) + return false; + + location->remove_voxel_if_exists(coordinate); + vpool->add_voxel(coordinate_id_pair_type(pid, coordinate)); + voxels_.at(coordinate) = vpool; + + return true; +} + +bool LatticeSpaceVectorImpl::add_voxels( + const Species &sp, + std::vector> voxels) +{ + // this function doesn't check location. + std::shared_ptr mtb; + try + { + mtb = find_voxel_pool(sp); + } + catch (NotFound &e) + { + return false; + } + + for (const auto &voxel : voxels) + { + const ParticleID pid(voxel.first); + const coordinate_type coord(voxel.second); + get_voxel_pool_at(coord)->remove_voxel_if_exists(coord); + mtb->add_voxel(coordinate_id_pair_type(pid, coord)); + voxels_.at(coord) = mtb; + } + return true; +} + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/triangle_geometry.cpp",".cpp","4836","182","#include ""triangle_geometry.hpp"" +#include + +namespace ecell4 +{ + +Real3 closest_point(const Real3& pos, const Triangle& tri) +{ + // this implementation is based on ""Real-Time Collision Detection"" + // by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.141-142 + + const Real3 a = tri.vertices()[0]; + const Real3 b = tri.vertices()[1]; + const Real3 c = tri.vertices()[2]; + + const Real3 ab = b - a; + const Real3 ac = c - a; + const Real3 ap = pos - a; + const Real d1 = dot_product(ab, ap); + const Real d2 = dot_product(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) + return a; + + const Real3 bp = pos - b; + const Real d3 = dot_product(ab, bp); + const Real d4 = dot_product(ac, bp); + if (d3 >= 0.0 && d4 <= d3) + return b; + + const Real vc = d1*d4 - d3*d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) + { + const Real v = d1 / (d1 - d3); + return a + ab * v; + } + + const Real3 cp = pos - c; + const Real d5 = dot_product(ab, cp); + const Real d6 = dot_product(ac, cp); + if (d6 >= 0.0 && d5 <= d6) + return c; + + const Real vb = d5*d2 - d1*d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) + { + const Real w = d2 / (d2 - d6); + return a + ac * w; + } + + const Real va = d3*d6 - d5*d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) + { + const Real w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return b + (c - b) * w; + } + + const Real denom = 1.0 / (va + vb + vc); + const Real v = vb * denom; + const Real w = vc * denom; + return a + ab * v + ac * w; +} + +Real3 closest_point(const Real3& pos, const TriangleView& tri) +{ + // this implementation is based on ""Real-Time Collision Detection"" + // by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.141-142 + + const Real3 a = tri.vertices(0); + const Real3 b = tri.vertices(1); + const Real3 c = tri.vertices(2); + + const Real3 ab = b - a; + const Real3 ac = c - a; + const Real3 ap = pos - a; + const Real d1 = dot_product(ab, ap); + const Real d2 = dot_product(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) + return a; + + const Real3 bp = pos - b; + const Real d3 = dot_product(ab, bp); + const Real d4 = dot_product(ac, bp); + if (d3 >= 0.0 && d4 <= d3) + return b; + + const Real vc = d1*d4 - d3*d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) + { + const Real v = d1 / (d1 - d3); + return a + ab * v; + } + + const Real3 cp = pos - c; + const Real d5 = dot_product(ab, cp); + const Real d6 = dot_product(ac, cp); + if (d6 >= 0.0 && d5 <= d6) + return c; + + const Real vb = d5*d2 - d1*d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) + { + const Real w = d2 / (d2 - d6); + return a + ac * w; + } + + const Real va = d3*d6 - d5*d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) + { + const Real w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return b + (c - b) * w; + } + + const Real denom = 1.0 / (va + vb + vc); + const Real v = vb * denom; + const Real w = vc * denom; + return a + ab * v + ac * w; +} + +Real3 closest_point(const Real3& pos, const TriangleConstView& tri) +{ + // this implementation is based on ""Real-Time Collision Detection"" + // by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.141-142 + + const Real3 a = tri.vertices(0); + const Real3 b = tri.vertices(1); + const Real3 c = tri.vertices(2); + + const Real3 ab = b - a; + const Real3 ac = c - a; + const Real3 ap = pos - a; + const Real d1 = dot_product(ab, ap); + const Real d2 = dot_product(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) + return a; + + const Real3 bp = pos - b; + const Real d3 = dot_product(ab, bp); + const Real d4 = dot_product(ac, bp); + if (d3 >= 0.0 && d4 <= d3) + return b; + + const Real vc = d1*d4 - d3*d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) + { + const Real v = d1 / (d1 - d3); + return a + ab * v; + } + + const Real3 cp = pos - c; + const Real d5 = dot_product(ab, cp); + const Real d6 = dot_product(ac, cp); + if (d6 >= 0.0 && d5 <= d6) + return c; + + const Real vb = d5*d2 - d1*d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) + { + const Real w = d2 / (d2 - d6); + return a + ac * w; + } + + const Real va = d3*d6 - d5*d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) + { + const Real w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return b + (c - b) * w; + } + + const Real denom = 1.0 / (va + vb + vc); + const Real v = vb * denom; + const Real w = vc * denom; + return a + ab * v + ac * w; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Shape.hpp",".hpp","917","48","#ifndef ECELL4_SHAPE_HPP +#define ECELL4_SHAPE_HPP + +#include ""Real3.hpp"" +#include ""RandomNumberGenerator.hpp"" + + +namespace ecell4 +{ + +struct Shape +{ + typedef enum + { + ONE = 1, + TWO = 2, + THREE = 3, + UNDEF = 4, + } dimension_kind; + + virtual ~Shape() + { + ; // do nothing + } + + virtual dimension_kind dimension() const = 0; + // virtual dimension_kind dimension() const + // { + // return THREE; + // } + + virtual Real is_inside(const Real3& coord) const = 0; + virtual Real3 draw_position( + std::shared_ptr& rng) const = 0; + virtual bool test_AABB(const Real3& l, const Real3& u) const = 0; + + virtual void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + lower = Real3(0.0, 0.0, 0.0); + upper = edge_lengths; + } +}; + +} // ecell4 + +#endif /* ECELL4_SHAPE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ReactionRule.hpp",".hpp","4808","169","#ifndef ECELL4_REACTION_RULE_HPP +#define ECELL4_REACTION_RULE_HPP + +#include ""ReactionRuleDescriptor.hpp"" + +#include ""types.hpp"" +#include ""Quantity.hpp"" +#include ""Species.hpp"" +#include ""Attribute.hpp"" +#include +#include + +namespace ecell4 +{ + +class ReactionRule +{ +public: + + /** + * a type of the container of reactants + * std::multiset allows multiple keys with equal values, + * but looses the original order at the registration. + * when changing this type into the ordered one, + * please modify NetworkModel too. + */ + typedef std::vector reactant_container_type; + typedef std::vector product_container_type; + +public: + + enum policy_type : long + { + POLICY_STRICT = 1L << 0, + POLICY_IMPLICIT = 1L << 1, + POLICY_DESTROY = 1L << 2 + }; + + typedef Attribute::mapped_type attribute_type; + +public: + + ReactionRule(); + ReactionRule(const reactant_container_type& reactants, + const product_container_type& products); + ReactionRule(const reactant_container_type& reactants, + const product_container_type& products, + const Real& k); + ReactionRule(const reactant_container_type& reactants, + const product_container_type& products, + const Quantity& k); + ReactionRule(const ReactionRule& rr); + + Real k() const; + void set_k(const Real& k); + void set_k(const Quantity& k); + Quantity get_k() const; + + const reactant_container_type& reactants() const; + const product_container_type& products() const; + void add_reactant(const Species& sp); + void add_product(const Species& sp); + + const policy_type policy() const; + void set_policy(const policy_type policy); + + const std::string as_string() const; + + Integer count(const reactant_container_type& reactants) const; + std::vector generate(const reactant_container_type& reactants) const; + + bool has_descriptor() const; + void set_descriptor(const std::shared_ptr& descriptor); + const std::shared_ptr& get_descriptor() const; + void reset_descriptor(); + + /** + * Attribute + */ + const Attribute& attributes() const; + void set_attributes(const Attribute& attr); + + std::vector > list_attributes() const; + attribute_type get_attribute(const std::string& key) const; + + template + T_ get_attribute_as(const std::string& key) const + { + return attributes_.get_as(key); + } + + template + void set_attribute(const std::string& key, T_ value) + { + attributes_.set(key, value); + } + + void remove_attribute(const std::string& key); + bool has_attribute(const std::string& key) const; + +protected: + + Quantity k_; + reactant_container_type reactants_; + product_container_type products_; + + policy_type policy_; + Attribute attributes_; + + std::shared_ptr rr_descriptor_; + // std::weak_ptr rr_descriptor_; +}; + +inline bool operator<(const ReactionRule& lhs, const ReactionRule& rhs) +{ + if (lhs.reactants() < rhs.reactants()) + { + return true; + } + else if (lhs.reactants() > rhs.reactants()) + { + return false; + } + return (lhs.products() < rhs.products()); +} + +inline bool operator==(const ReactionRule& lhs, const ReactionRule& rhs) +{ + return ((lhs.reactants() == rhs.reactants()) + && (lhs.products() == rhs.products())); +} + +inline bool operator!=(const ReactionRule& lhs, const ReactionRule& rhs) +{ + return !(lhs == rhs); +} + +constexpr ReactionRule::policy_type operator|(ReactionRule::policy_type lhs, ReactionRule::policy_type rhs) +{ + return static_cast(static_cast(lhs) | static_cast(rhs)); +} + +ReactionRule format_reaction_rule_with_nosort(const ReactionRule& rr); +ReactionRule format_reaction_rule(const ReactionRule& rr); + +ReactionRule create_unimolecular_reaction_rule( + const Species& reactant1, const Species& product1, const Real& k); + +ReactionRule create_binding_reaction_rule( + const Species& reactant1, const Species& reactant2, const Species& product1, + const Real& k); + +ReactionRule create_unbinding_reaction_rule( + const Species& reactant1, const Species& product1, const Species& product2, + const Real& k); + +ReactionRule create_degradation_reaction_rule( + const Species& reactant1, const Real& k); + +ReactionRule create_synthesis_reaction_rule( + const Species& product1, const Real& k); + +// ReactionRule create_repulsive_reaction_rule( +// const Species& reactant1, const Species& reactant2); + +} // ecell4 + +#endif /* ECELL4_REACTION_RULE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/SubvolumeSpace.cpp",".cpp","10491","378","#include +#include ""SubvolumeSpace.hpp"" +#include ""Context.hpp"" + +namespace ecell4 +{ + +Integer SubvolumeSpaceVectorImpl::num_molecules(const Species& sp) const +{ + SpeciesExpressionMatcher sexp(sp); + Integer retval(0); + for (matrix_type::const_iterator i(matrix_.begin()); + i != matrix_.end(); ++i) + { + retval += (*i).second->num_molecules() * sexp.count((*i).first); + } + return retval; +} + +Integer SubvolumeSpaceVectorImpl::num_molecules_exact(const Species& sp) const +{ + matrix_type::const_iterator i(matrix_.find(sp)); + if (i == matrix_.end()) + { + return 0; + } + // return std::accumulate((*i).second.begin(), (*i).second.end(), 0); + return (*i).second->num_molecules(); +} + +Integer SubvolumeSpaceVectorImpl::num_molecules( + const Species& sp, const coordinate_type& c) const +{ + SpeciesExpressionMatcher sexp(sp); + Integer retval(0); + for (matrix_type::const_iterator i(matrix_.begin()); + i != matrix_.end(); ++i) + { + retval += (*i).second->num_molecules(c) * sexp.count((*i).first); + } + return retval; +} + +Integer SubvolumeSpaceVectorImpl::num_molecules_exact( + const Species& sp, const coordinate_type& c) const +{ + matrix_type::const_iterator i(matrix_.find(sp)); + if (i == matrix_.end()) + { + return 0; + } + // return (*i).second[c]; + return (*i).second->num_molecules(c); +} + +const std::shared_ptr& +SubvolumeSpaceVectorImpl::get_pool(const Species& sp) const +{ + matrix_type::const_iterator i(matrix_.find(sp)); + if (i == matrix_.end()) + { + throw_exception(""Speices ["", sp.serial(), ""] not found""); + } + return (*i).second; +} + +const std::shared_ptr +SubvolumeSpaceVectorImpl::reserve_pool( + const Species& sp, const Real D, const Species::serial_type& loc) +{ + matrix_type::const_iterator i(matrix_.find(sp)); + if (i != matrix_.end()) + { + throw AlreadyExists(""Species already exists""); + } + // matrix_.insert(std::make_pair(sp, std::vector(num_subvolumes()))); + const std::shared_ptr pool(new Pool(sp, D, loc, num_subvolumes())); + matrix_.insert(std::make_pair(sp, pool)); + species_.push_back(sp); + return pool; +} + +void SubvolumeSpaceVectorImpl::add_molecules( + const Species& sp, const Integer& num, const coordinate_type& c) +{ + matrix_type::iterator i(matrix_.find(sp)); + if (i == matrix_.end()) + { + if (has_structure(sp)) + { + return; + } + + // reserve_species(sp, c); + // i = matrix_.find(sp); + throw_exception(""Speices ["", sp.serial(), ""] not found""); + } + // (*i).second[c] += num; + (*i).second->add_molecules(num, c); +} + +void SubvolumeSpaceVectorImpl::remove_molecules( + const Species& sp, const Integer& num, const coordinate_type& c) +{ + matrix_type::iterator i(matrix_.find(sp)); + if (i == matrix_.end()) + { + if (has_structure(sp)) + { + return; + } + throw_exception(""Speices ["", sp.serial(), ""] not found""); + } + + // if ((*i).second[c] < num) + if ((*i).second->num_molecules(c) < num) + { + throw_exception( + ""The number of molecules cannot be negative. ["", sp.serial(), ']'); + } + + // (*i).second[c] -= num; + (*i).second->remove_molecules(num, c); +} + +SubvolumeSpaceVectorImpl::coordinate_type SubvolumeSpaceVectorImpl::get_neighbor( + const coordinate_type& c, const Integer rnd) const +{ + Integer3 g(coord2global(c)); + + switch (rnd) + { + case 0: + return global2coord(g.east()); + case 1: + return global2coord(g.west()); + case 2: + return global2coord(g.south()); + case 3: + return global2coord(g.north()); + case 4: + return global2coord(g.dorsal()); + case 5: + return global2coord(g.ventral()); + } + + throw IllegalState(""the number of neighbors is less than 6.""); +} + +std::vector +SubvolumeSpaceVectorImpl::list_coordinates(const Species& sp) const +{ + SpeciesExpressionMatcher sexp(sp); + std::vector retval; + for (matrix_type::const_iterator i(matrix_.begin()); + i != matrix_.end(); ++i) + { + Integer cnt(sexp.count((*i).first)); + if (cnt > 0) + { + const std::vector coords = (*i).second->list_coordinates(); + for (; cnt > 0; --cnt) + { + retval.insert(retval.end(), coords.begin(), coords.end()); + } + // for (cell_type::size_type j(0); j < (*i).second.size(); ++j) + // { + // if ((*i).second[j] > 0) + // { + // retval.resize(retval.size() + (*i).second[j] * cnt, j); + // } + // } + } + } + return retval; +} + +std::vector +SubvolumeSpaceVectorImpl::list_coordinates_exact(const Species& sp) const +{ + std::vector retval; + matrix_type::const_iterator i(matrix_.find(sp)); + if (i == matrix_.end()) + { + return retval; + } + return (*i).second->list_coordinates(); + + // for (cell_type::size_type j(0); j < (*i).second.size(); ++j) + // { + // if ((*i).second[j] > 0) + // { + // retval.resize(retval.size() + (*i).second[j], j); + // } + // } + // return retval; +} + +void SubvolumeSpaceVectorImpl::add_structure( + const Species& sp, const std::shared_ptr& shape) +{ + structure_matrix_type::const_iterator it(structure_matrix_.find(sp.serial())); + if (it != structure_matrix_.end()) + { + throw_exception(""The given structure ["", sp.serial(), + ""] is already defined.""); + } + + switch (shape->dimension()) + { + case Shape::THREE: + add_structure3(sp, shape); + return; + case Shape::TWO: + add_structure2(sp, shape); + return; + case Shape::ONE: + case Shape::UNDEF: + break; + } + + throw NotSupported(""The dimension of a shape must be two or three.""); +} + +void SubvolumeSpaceVectorImpl::add_structure3( + const Species& sp, const std::shared_ptr& shape) +{ + structure_cell_type overlap(num_subvolumes()); + for (structure_cell_type::size_type i(0); i != overlap.size(); ++i) + { + if (shape->is_inside(coord2position(i)) > 0) + { + overlap[i] = 0; + } + else + { + overlap[i] = 1; + } + } + // structures_.insert(std::make_pair(sp.serial(), Shape::THREE)); + structure_matrix_.insert(std::make_pair(sp.serial(), overlap)); +} + +void SubvolumeSpaceVectorImpl::add_structure2( + const Species& sp, const std::shared_ptr& shape) +{ + structure_cell_type overlap(num_subvolumes()); + for (structure_cell_type::size_type i(0); i != overlap.size(); ++i) + { + if (is_surface_subvolume(i, shape)) + { + // overlap[i] = 1; + overlap[i] = unit_area(); + } + else + { + overlap[i] = 0; + } + } + // structures_.insert(std::make_pair(sp.serial(), Shape::TWO)); + structure_matrix_.insert(std::make_pair(sp.serial(), overlap)); +} + +bool SubvolumeSpaceVectorImpl::is_surface_subvolume( + const coordinate_type& c, const std::shared_ptr& shape) +{ + const Real3 lengths(subvolume_edge_lengths()); + const Real3 center(coord2position(c)); + + if (shape->is_inside(center) > 0) + { + return false; + } + + for (unsigned int dim(0); dim < 3 * 3 * 3; ++dim) + { + const int x(static_cast(dim / 9)); + const int y(static_cast((dim - x * 9) / 3)); + const int z(dim - (x * 3 + y) * 3); + + if ((x == 1 && y == 1 && z == 1) + || (x != 1 && y != 1 && z != 1)) + { + continue; + } + + const Real3 shift( + (x - 1) * lengths[0], (y - 1) * lengths[1], (z - 1) * lengths[2]); + const Real3 neighbor = center + shift; + if (shape->is_inside(neighbor) > 0) + { + return true; + } + } + return false; +} + +bool SubvolumeSpaceVectorImpl::check_structure( + const Species::serial_type& serial, + const SubvolumeSpaceVectorImpl::coordinate_type& coord) const +{ + if (serial == """") + { + ; // This is for default structure. + return true; + } + + structure_matrix_type::const_iterator i(structure_matrix_.find(serial)); + if (i == structure_matrix_.end()) + { + return false; + } + return ((*i).second[coord] > 0); +} + +void SubvolumeSpaceVectorImpl::update_structure( + const Species::serial_type& serial, const coordinate_type& coord, + const Real& value) +{ + structure_matrix_type::iterator i(structure_matrix_.find(serial)); + if (i == structure_matrix_.end()) + { + structure_cell_type overlap(num_subvolumes()); + overlap[coord] = value; + structure_matrix_.insert(std::make_pair(serial, overlap)); + // structures_.insert(std::make_pair(serial, Shape::THREE)); //XXX: as a default + } + else + { + (*i).second[coord] = value; + } +} + +std::vector SubvolumeSpaceVectorImpl::list_structures() const +{ + std::vector retval; + for (structure_matrix_type::const_iterator i(structure_matrix_.begin()); + i != structure_matrix_.end(); ++i) + { + retval.push_back((*i).first); + } + return retval; +} + +Real SubvolumeSpaceVectorImpl::get_volume(const Species& sp) const +{ + structure_matrix_type::const_iterator i(structure_matrix_.find(sp.serial())); + if (i == structure_matrix_.end()) + { + return 0.0; + } + const Real occupancy = std::accumulate((*i).second.begin(), (*i).second.end(), 0.0); + return subvolume() * occupancy; +} + +const Integer SubvolumeSpaceVectorImpl::num_subvolumes(const Species& sp) const +{ + structure_matrix_type::const_iterator i(structure_matrix_.find(sp.serial())); + if (i == structure_matrix_.end()) + { + return 0; + } + + Integer num(0); + for (structure_cell_type::const_iterator j((*i).second.begin()); + j != (*i).second.end(); ++j) + { + if (*j > 0) + { + ++num; + } + } + return num; + // return std::accumulate((*i).second.begin(), (*i).second.end(), 0); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/SubvolumeSpaceHDF5Writer.hpp",".hpp","12686","310","#ifndef ECELL4_SUBVOLUME_SPACE_HDF5_WRITER_HPP +#define ECELL4_SUBVOLUME_SPACE_HDF5_WRITER_HPP + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include ""Species.hpp"" +#include ""types.hpp"" + +#include ""Space.hpp"" // just for Space::space_kind + +namespace ecell4 +{ + +struct SubvolumeSpaceHDF5Traits +{ + typedef struct h5_species_struct + { + uint32_t id; + char serial[32]; // species' serial may exceed the limit + double D; + char loc[32]; // species' loc may exceed the limit + } h5_species_struct; + + static H5::CompType get_species_comp_type() + { + H5::CompType h5_species_comp_type(sizeof(h5_species_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(h5_species_comp_type.getId(), #member, \ + HOFFSET(h5_species_struct, member), type.getId()) + INSERT_MEMBER(id, H5::PredType::STD_I32LE); + INSERT_MEMBER(serial, H5::StrType(H5::PredType::C_S1, 32)); + INSERT_MEMBER(D, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(loc, H5::StrType(H5::PredType::C_S1, 32)); +#undef INSERT_MEMBER + // h5_species_comp_type.insertMember( + // std::string(""id""), HOFFSET(h5_species_struct, id), + // H5::PredType::STD_I32LE); + // h5_species_comp_type.insertMember( + // std::string(""serial""), HOFFSET(h5_species_struct, serial), + // H5::StrType(H5::PredType::C_S1, 32)); + // h5_species_comp_type.insertMember( + // std::string(""D""), HOFFSET(h5_species_struct, D), + // H5::PredType::STD_I64LE); //XXX: -> NATIVE_DOUBLE? + // h5_species_comp_type.insertMember( + // std::string(""loc""), HOFFSET(h5_species_struct, loc), + // H5::StrType(H5::PredType::C_S1, 32)); + return h5_species_comp_type; + } + + typedef struct h5_structures_struct + { + uint32_t id; + char serial[32]; // structures' serial may exceed the limit + // uint32_t dimension; + } h5_structures_struct; + + static H5::CompType get_structures_comp_type() + { + H5::CompType h5_structures_comp_type(sizeof(h5_structures_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(h5_structures_comp_type.getId(), #member, \ + HOFFSET(h5_structures_struct, member), type.getId()) + INSERT_MEMBER(id, H5::PredType::STD_I32LE); + INSERT_MEMBER(serial, H5::StrType(H5::PredType::C_S1, 32)); + // INSERT_MEMBER(dimension, H5::PredType::STD_I32LE); +#undef INSERT_MEMBER + // h5_structures_comp_type.insertMember( + // std::string(""id""), HOFFSET(h5_structures_struct, id), + // H5::PredType::STD_I32LE); + // h5_structures_comp_type.insertMember( + // std::string(""serial""), HOFFSET(h5_structures_struct, serial), + // H5::StrType(H5::PredType::C_S1, 32)); + // // h5_species_comp_type.insertMember( + // // std::string(""dimension""), HOFFSET(h5_structure_struct, + // dimension), + // // H5::PredType::STD_I32LE); + return h5_structures_comp_type; + } +}; + +template +void save_subvolume_space(const Tspace_ &space, H5::Group *root) +{ + typedef SubvolumeSpaceHDF5Traits traits_type; + typedef typename traits_type::h5_species_struct h5_species_struct; + // typedef typename traits_type::h5_voxel_struct h5_voxel_struct; + typedef typename traits_type::h5_structures_struct h5_structures_struct; + + const unsigned int num_subvolumes(space.num_subvolumes()); + const std::vector species(space.list_species()); + boost::multi_array h5_num_table( + boost::extents[species.size()][num_subvolumes]); + std::unique_ptr h5_species_table( + new h5_species_struct[species.size()]); + + for (unsigned int i(0); i < species.size(); ++i) + { + const unsigned int sid(i + 1); + h5_species_table[i].id = sid; + std::strcpy(h5_species_table[i].serial, species[i].serial().c_str()); + const std::shared_ptr &pool = + space.get_pool(species[i]); + h5_species_table[i].D = pool->D(); + std::strcpy(h5_species_table[i].loc, pool->loc().c_str()); + + for (unsigned int j(0); j < num_subvolumes; ++j) + { + h5_num_table[i][j] = space.num_molecules_exact(species[i], j); + } + } + + const std::vector structures(space.list_structures()); + boost::multi_array h5_stcoordinate_table( + boost::extents[structures.size()][num_subvolumes]); + std::unique_ptr h5_structures_table( + new h5_structures_struct[structures.size()]); + for (unsigned int i(0); i < structures.size(); ++i) + { + const unsigned int sid(i + 1); + h5_structures_table[i].id = sid; + std::strcpy(h5_structures_table[i].serial, structures[i].c_str()); + // h5_structures_table[i].dimension = + // space.get_dimension(structures[i]); + for (unsigned int j(0); j < num_subvolumes; ++j) + { + // const bool exist = space.check_structure(structures[i], j); + // h5_stcoordinate_table[i][j] = (exist ? 1 : 0); + h5_stcoordinate_table[i][j] = space.get_occupancy(structures[i], j); + } + } + + const int RANK1 = 2; + const int RANK2 = 1; + + hsize_t dim1[] = {species.size(), num_subvolumes}; + H5::DataSpace dataspace1(RANK1, dim1); + std::unique_ptr dataset1(new H5::DataSet(root->createDataSet( + ""num_molecules"", H5::PredType::STD_I64LE, dataspace1))); + + hsize_t dim2[] = {species.size()}; + H5::DataSpace dataspace2(RANK2, dim2); + std::unique_ptr dataset2(new H5::DataSet(root->createDataSet( + ""species"", traits_type::get_species_comp_type(), dataspace2))); + + hsize_t dim3[] = {structures.size(), num_subvolumes}; + H5::DataSpace dataspace3(RANK1, dim3); + std::unique_ptr dataset3(new H5::DataSet(root->createDataSet( + ""stcoordinates"", H5::PredType::IEEE_F64LE, dataspace3))); + + hsize_t dim4[] = {structures.size()}; + H5::DataSpace dataspace4(RANK2, dim4); + std::unique_ptr dataset4(new H5::DataSet(root->createDataSet( + ""structures"", traits_type::get_structures_comp_type(), dataspace4))); + + dataset1->write(h5_num_table.data(), dataset1->getDataType()); + dataset2->write(h5_species_table.get(), dataset2->getDataType()); + dataset3->write(h5_stcoordinate_table.data(), dataset3->getDataType()); + dataset4->write(h5_structures_table.get(), dataset4->getDataType()); + + const uint32_t space_type = static_cast(Space::SUBVOLUME); + H5::Attribute attr_space_type(root->createAttribute( + ""type"", H5::PredType::STD_I32LE, H5::DataSpace(H5S_SCALAR))); + attr_space_type.write(H5::PredType::STD_I32LE, &space_type); + + const double t = space.t(); + H5::Attribute attr_t(root->createAttribute(""t"", H5::PredType::IEEE_F64LE, + H5::DataSpace(H5S_SCALAR))); + attr_t.write(H5::PredType::IEEE_F64LE, &t); + + const Real3 edge_lengths = space.edge_lengths(); + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + H5::Attribute attr_lengths(root->createAttribute( + ""edge_lengths"", lengths_type, H5::DataSpace(H5S_SCALAR))); + double lengths[] = {edge_lengths[0], edge_lengths[1], edge_lengths[2]}; + attr_lengths.write(lengths_type, lengths); + + const Integer3 matrix_sizes = space.matrix_sizes(); + const H5::ArrayType sizes_type(H5::PredType::STD_I64LE, 1, dims); + H5::Attribute attr_sizes(root->createAttribute(""matrix_sizes"", sizes_type, + H5::DataSpace(H5S_SCALAR))); + int64_t sizes[] = {matrix_sizes.col, matrix_sizes.row, matrix_sizes.layer}; + attr_sizes.write(sizes_type, sizes); +} + +template +void load_subvolume_space(const H5::Group &root, Tspace_ *space) +{ + typedef SubvolumeSpaceHDF5Traits traits_type; + typedef typename traits_type::h5_species_struct h5_species_struct; + typedef typename traits_type::h5_structures_struct h5_structures_struct; + // typedef typename traits_type::h5_voxel_struct h5_voxel_struct; + + Real3 edge_lengths; + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + root.openAttribute(""edge_lengths"").read(lengths_type, &edge_lengths); + + int64_t sizes[3]; + const H5::ArrayType sizes_type(H5::PredType::STD_I64LE, 1, dims); + root.openAttribute(""matrix_sizes"").read(sizes_type, sizes); + const Integer3 matrix_sizes(sizes[0], sizes[1], sizes[2]); + + space->reset(edge_lengths, matrix_sizes); + + double t; + root.openAttribute(""t"").read(H5::PredType::IEEE_F64LE, &t); + space->set_t(t); + + { + H5::DataSet species_dset(root.openDataSet(""species"")); + const unsigned int num_species( + species_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr h5_species_table( + new h5_species_struct[num_species]); + species_dset.read(h5_species_table.get(), + traits_type::get_species_comp_type()); + species_dset.close(); + + H5::DataSet num_dset(root.openDataSet(""num_molecules"")); + hsize_t dims[2]; + num_dset.getSpace().getSimpleExtentDims(dims); + assert(num_species == dims[0]); + const unsigned int num_subvolumes(dims[1]); + boost::multi_array h5_num_table( + boost::extents[num_species][num_subvolumes]); + num_dset.read(h5_num_table.data(), H5::PredType::STD_I64LE); + num_dset.close(); + + typedef std::unordered_map + species_id_map_type; + species_id_map_type species_id_map; + for (unsigned int i(0); i < num_species; ++i) + { + // species_id_map[h5_species_table[i].id] = + // h5_species_table[i].serial; + species_id_map[h5_species_table[i].id] = i; + } + + for (unsigned int i(0); i < num_species; ++i) + { + const uint32_t sid(i + 1); + const unsigned int k(species_id_map[sid]); + + const Species sp(h5_species_table[k].serial); + const Real D(h5_species_table[k].D); + const Species::serial_type loc(h5_species_table[k].loc); + space->reserve_pool(sp, D, loc); + + for (unsigned int j(0); j < num_subvolumes; ++j) + { + space->add_molecules(sp, h5_num_table[i][j], j); + } + } + } + + { + H5::DataSet structures_dset(root.openDataSet(""structures"")); + const unsigned int num_structures( + structures_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr h5_structures_table( + new h5_structures_struct[num_structures]); + structures_dset.read(h5_structures_table.get(), + traits_type::get_structures_comp_type()); + structures_dset.close(); + + H5::DataSet stcoordinate_dset(root.openDataSet(""stcoordinates"")); + hsize_t dims[2]; + stcoordinate_dset.getSpace().getSimpleExtentDims(dims); + assert(num_structures == dims[0]); + const unsigned int num_subvolumes(dims[1]); + boost::multi_array h5_stcoordinate_table( + boost::extents[num_structures][num_subvolumes]); + stcoordinate_dset.read(h5_stcoordinate_table.data(), + H5::PredType::IEEE_F64LE); + stcoordinate_dset.close(); + + typedef std::unordered_map + structures_id_map_type; + structures_id_map_type structures_id_map; + for (unsigned int i(0); i < num_structures; ++i) + { + structures_id_map[h5_structures_table[i].id] = + h5_structures_table[i].serial; + } + + for (unsigned int i(0); i < num_structures; ++i) + { + const uint32_t sid(i + 1); + const Species::serial_type serial(structures_id_map[sid]); + for (unsigned int j(0); j < num_subvolumes; ++j) + { + space->update_structure(serial, j, h5_stcoordinate_table[i][j]); + } + } + } +} + +} // namespace ecell4 + +#endif /* ECELL4_SUBVOLUME_SPACE_HDF5_WRITER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Attribute.cpp",".cpp","2895","141","#include ""Attribute.hpp"" + +#include + + +namespace ecell4 +{ + +Attribute::Attribute() + : data_() +{ + ; // do nothing +} + +Attribute::Attribute(const Attribute& another) + : data_(another.data_) +{ + ; +} + +Attribute::Attribute(const Attribute::container_type& attr) + : data_(attr) +{ + ; +} + +Attribute& Attribute::operator=(const Attribute& another) +{ + data_ = another.data_; + return *this; +} + +std::vector Attribute::values() const +{ + std::vector retval; + for (container_type::const_iterator + i(data_.begin()); i != data_.end(); ++i) + { + retval.push_back(*i); + } + return retval; +} + +Attribute::mapped_type Attribute::get(const key_type& key) const +{ + container_type::const_iterator + i(data_.find(key)); + if (i == data_.end()) + { + throw_exception(""attribute ["", key, ""] not found""); + } + + return (*i).second; +} + +void Attribute::clear() +{ + data_.clear(); +} + +void Attribute::overwrite(const Attribute& attr) +{ + const container_type& attrs(attr.data_); + for (container_type::const_iterator i(attrs.begin()); + i != attrs.end(); ++i) + { + this->set((*i).first, (*i).second); + } +} + +void Attribute::remove(const key_type& key) +{ + container_type::iterator + i(data_.find(key)); + if (i == data_.end()) + { + throw_exception(""attribute ["", key, ""] not found""); + } + + data_.erase(i); +} + +bool Attribute::has_key(const key_type& key) const +{ + return (data_.find(key) != data_.end()); +} + +template <> +Real Attribute::get_as(const key_type& key) const +{ + mapped_type val = get(key); + if (Quantity* x = boost::get >(&val)) + { + return (*x).magnitude; + } + else if (Quantity* x = boost::get >(&val)) + { + return static_cast((*x).magnitude); + } + else if (std::string* x = boost::get(&val)) + { + return std::atof((*x).c_str()); + } + throw NotSupported(""An attribute has incorrect type. Real is expected""); +} + +template <> +Integer Attribute::get_as(const key_type& key) const +{ + mapped_type val = get(key); + if (Quantity* x = boost::get >(&val)) + { + return (*x).magnitude; + } + else if (std::string* x = boost::get(&val)) + { + return std::atoi((*x).c_str()); + } + throw NotSupported(""An attribute has incorrect type. Integer is expected""); +} + +template <> +void Attribute::set(const key_type& key, const char* value) +{ + set(key, std::string(value)); +} + +template <> +void Attribute::set(const key_type& key, const Real value) +{ + set(key, Quantity(value)); +} + +template <> +void Attribute::set(const key_type& key, const Integer value) +{ + set(key, Quantity(value)); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/PlanarSurface.hpp",".hpp","1010","57","#ifndef ECELL4_PLANAR_SURFACE_HPP +#define ECELL4_PLANAR_SURFACE_HPP + +#include ""Shape.hpp"" + +namespace ecell4 +{ + +struct PlanarSurface + : public Shape +{ + + PlanarSurface(); + PlanarSurface(const Real3& origin, const Real3& e0, const Real3& e1); + PlanarSurface(const PlanarSurface& rhs); + Real is_inside(const Real3& coord) const; + Real3 draw_position( + std::shared_ptr& rng) const; + bool test_AABB(const Real3& lower, const Real3& upper) const; + void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& u) const; + + const Real3& origin() const + { + return origin_; + } + + const Real3& e0() const + { + return e0_; + } + + const Real3& e1() const + { + return e1_; + } + + const Real3& normal() const + { + return n_; + } + + dimension_kind dimension() const + { + return TWO; + } + +protected: + + Real3 origin_, e0_, e1_, n_; + Real d_; +}; + +} + +#endif /* ECELL4_PLANAR_SURFACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Attribute.hpp",".hpp","2396","95","#ifndef ECELL4_ATTRIBUTE_HPP +#define ECELL4_ATTRIBUTE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +// #include + +#include + +#include ""types.hpp"" +#include ""exceptions.hpp"" +#include ""Quantity.hpp"" + + +namespace ecell4 +{ + +class Attribute +{ +public: + + typedef std::string key_type; + typedef boost::variant, Quantity, bool> mapped_type; + +protected: + + typedef boost::container::flat_map + container_type; + + // typedef boost::container::small_vector< + // std::pair, 3 + // > flat_map_backend_type; + // typedef boost::container::flat_map< + // key_type, mapped_type, std::less, flat_map_backend_type + // > container_type; + +public: + + typedef container_type::value_type value_type; + +public: + + Attribute(); + Attribute(const Attribute& another); + Attribute& operator=(const Attribute& another); + Attribute(const container_type& attr); + + std::vector values() const; + mapped_type get(const key_type& name_attr) const; + + template + T_ get_as(const key_type& name_attr) const + { + mapped_type val = get(name_attr); + if (T_* x = boost::get(&val)) + { + return (*x); + } + throw NotSupported(""An attribute has incorrect type.""); + } + + template + void set(const key_type& name_attr, T_ value) + { + data_[name_attr] = value; + } + + void remove(const key_type& name_attr); + bool has_key(const key_type& name_attr) const; + void overwrite(const Attribute& attr); + void clear(); + +protected: + + container_type data_; +}; + +template <> Real Attribute::get_as(const key_type& name_attr) const; +template <> Integer Attribute::get_as(const key_type& name_attr) const; +template <> void Attribute::set(const key_type& name_attr, const char* value); +template <> void Attribute::set(const key_type& name_attr, const Real value); +template <> void Attribute::set(const key_type& name_attr, const Integer value); + +} // ecell4 + + +#endif /* ECELL4_ATTRIBUTE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Context.cpp",".cpp","42275","1291","#include ""Context.hpp"" +#include +#include + + +namespace ecell4 +{ + +namespace context +{ + +std::string itos(unsigned int val) +{ + std::stringstream ss; + ss << val; + return ss.str(); +} + +unsigned int concatenate_units(std::vector& units1, const Species& sp, const unsigned int bond_stride) +{ + const std::vector units2 = sp.units(); + units1.reserve(units1.size() + units2.size()); + + std::unordered_map bond_cache; + + for (Species::container_type::const_iterator j(units2.begin()); + j != units2.end(); ++j) + { + units1.push_back(*j); + + for (UnitSpecies::container_type::const_iterator + k((*j).begin()); k != (*j).end(); ++k) + { + const std::string& bond((*k).second.second); + if (bond != """" && !is_wildcard(bond)) + { + std::unordered_map::const_iterator + it = bond_cache.find(bond); + if (it == bond_cache.end()) + { + const std::string newbond = itos(bond_stride + 1 + bond_cache.size()); + bond_cache.insert(std::make_pair(bond, newbond)); + units1.back().at(std::distance((*j).begin(), k)).second.second = newbond; + } + else + { + units1.back().at(std::distance((*j).begin(), k)).second.second = (*it).second; + } + } + } + } + return bond_cache.size(); +} + +unsigned int tag_units( + std::vector& groups, + const unsigned int& group_id, + const unsigned int& idx, + const std::vector::size_type> >& connections, + const unsigned int& notyet) +{ + if (groups[idx] != notyet) + { + // assert(groups[idx] < group_id); + return group_id; + } + + groups[idx] = group_id; + + for (std::vector::size_type>::const_iterator + i(connections[idx].begin()); i != connections[idx].end(); ++i) + { + tag_units(groups, group_id, *i, connections, notyet); + // const unsigned int _gid = tag_units(groups, group_id, *i, connections, notyet); + // assert(_gid == group_id); + } + + return group_id + 1; +} + +bool is_correspondent(const UnitSpecies& usp1, const UnitSpecies& usp2) +{ + if (usp1.name() != usp2.name() || usp1.num_sites() != usp2.num_sites()) + { + return false; + } + + for (UnitSpecies::container_type::const_iterator + i(usp1.begin()), j(usp2.begin()); i != usp1.end() && j != usp2.end(); ++i, ++j) + { + if ((*i).first != (*j).first) + { + return false; + } + } + return true; +} + +// struct species_formatter +// { +// typedef std::vector::size_type size_type; +// +// struct bond_type +// { +// std::string name; +// size_type one; +// size_type another; +// +// bond_type() +// {} +// +// bond_type(const std::string& name, const size_type one, const size_type another) +// : name(name), one(one), another(another) +// {} +// }; +// +// typedef std::unordered_map bond_container_type; +// +// species_formatter(const std::vector& units) +// : units(units) +// { +// bonds.clear(); +// for (size_type idx = 0; idx != units.size(); ++idx) +// { +// const UnitSpecies& unit(units.at(idx)); +// for (UnitSpecies::container_type::const_iterator i(unit.begin()); +// i != unit.end(); ++i) +// { +// const std::string& bond = (*i).second.second; +// +// if (is_empty(bond) || is_wildcard(bond)) +// { +// continue; +// } +// +// bond_container_type::iterator it = bonds.find(bond); +// if (it == bonds.end()) +// { +// bonds.insert(std::make_pair(bond, bond_type(bond, idx, units.size()))); +// } +// else +// { +// (*it).second.another = idx; +// } +// } +// } +// } +// +// size_type get_partner(const std::string bond, const size_type one) const +// { +// bond_container_type::const_iterator i = bonds.find(bond); +// assert(i != bonds.end()); +// const bond_type& b = (*i).second; +// if (b.one == one) +// { +// assert(b.another != units.size()); +// return b.another; +// } +// else +// { +// assert(b.one != units.size()); +// return b.one; +// } +// } +// +// // std::vector sort(const size_type start) const +// // { +// // std::vector permutation(units.size(), units.size()); +// +// // size_type stride = sort(permutation, start, 0); +// // for (size_type idx = 0; idx != units.size(); ++idx) +// // { +// // stride = sort(permutation, idx, stride); +// // } +// +// // assert(stride == units.size()); +// // return permutation; +// // } +// +// size_type sort(std::vector& permutation, const size_type pos, const size_type idx) const +// { +// if (permutation[pos] != units.size()) +// { +// return idx; +// } +// +// permutation[pos] = idx; +// size_type stride = idx + 1; +// const UnitSpecies& unit = units.at(pos); +// for (UnitSpecies::container_type::const_iterator i(unit.begin()); +// i != unit.end(); ++i) +// { +// const std::string& bond = (*i).second.second; +// +// if (is_empty(bond) || is_wildcard(bond)) +// { +// continue; +// } +// +// stride = sort(permutation, get_partner(bond, pos), stride); +// } +// return stride; +// } +// +// Species collect(const std::vector& permutation) const +// { +// typedef std::unordered_map mapper_type; +// mapper_type bond_names; +// +// std::vector res; +// for (size_type i = 0; i != permutation.size(); ++i) +// { +// const size_type& j = permutation.at(i); +// if (j == units.size()) +// { +// continue; +// } +// else if (j >= res.size()) +// { +// res.resize(j + 1); +// } +// res[j] = units[i]; +// } +// +// unsigned int stride = 0; +// Species sp; +// for (std::vector::iterator i = res.begin(); +// i != res.end(); ++i) +// { +// UnitSpecies& unit = (*i); +// +// for (UnitSpecies::container_type::iterator k(unit.begin()); +// k != unit.end(); ++k) +// { +// std::string& bond = (*k).second.second; +// +// if (is_empty(bond) || is_wildcard(bond)) +// { +// continue; +// } +// +// mapper_type::const_iterator +// it = bond_names.find(bond); +// if (it == bond_names.end()) +// { +// const std::string new_bond_name = itos(++stride); +// bond_names.insert(std::make_pair(bond, new_bond_name)); +// bond = new_bond_name; +// } +// else +// { +// bond = (*it).second; +// } +// } +// +// sp.add_unit(unit); +// } +// +// return sp; +// } +// +// const std::vector& units; +// bond_container_type bonds; +// }; + +class species_structure +{ +public: + + // typedef Species::container_type::size_type index_type; + typedef unsigned int index_type; + typedef std::pair site_type; + typedef std::unordered_map> + connection_container_type; + +public: + + species_structure(const Species& sp) + : root_(sp.units()) + { + initialize(); + } + + const std::vector& units() const + { + return root_; + } + + void initialize() + { + connections_.clear(); + for (index_type idx(0); idx < root_.size(); ++idx) + { + const UnitSpecies usp(root_.at(idx)); + for (UnitSpecies::container_type::const_iterator i(usp.begin()); + i != usp.end(); ++i) + { + if ((*i).second.second == """" || is_wildcard((*i).second.second)) + { + continue; + } + + if (connections_.find((*i).second.second) == connections_.end()) + { + connections_.insert(std::make_pair( + (*i).second.second, std::vector())); + } + connections_[(*i).second.second].push_back( + std::make_pair(idx, (*i).first)); + } + } + } + + int compare(const index_type& val1, const index_type& val2) + { + if (val1 == val2) + { + return 0; + } + + const std::pair pair_key((val1 < val2)? + std::make_pair(val1, val2) : std::make_pair(val1, val2)); + if (std::binary_search(ignores_.begin(), ignores_.end(), pair_key)) + { + return 0; + } + + const UnitSpecies& lhs(root_.at(val1)); + const UnitSpecies& rhs(root_.at(val2)); + + if (lhs.name() != rhs.name()) + { + return (lhs.name() < rhs.name()? 1 : -1); + } + + UnitSpecies::container_type::const_iterator + i(lhs.begin()), j(rhs.begin()); + while (i != lhs.end() && j != rhs.end()) + { + if ((*i).first != (*j).first) + { + // std::cout << ""[1] "" << lhs.serial() << ""("" << val1 << "") vs "" + // << rhs.serial() << ""("" << val2 << "") -> "" << (*i).first + // << "" < "" << (*j).first << std::endl; + return ((*i).first < (*j).first? 1 : -1); + } + else if ((*i).second.first != (*j).second.first) + { + // std::cout << ""[2] "" << lhs.serial() << ""("" << val1 << "") vs "" + // << rhs.serial() << ""("" << val2 << "")"" << std::endl; + return ((*i).second.first < (*j).second.first? 1 : -1); + } + else if (((*i).second.second == """") != ((*j).second.second == """")) + { + // std::cout << ""[3] "" << lhs.serial() << ""("" << val1 << "") vs "" + // << rhs.serial() << ""("" << val2 << "") -> '"" + // << (*i).second.second << ""' < '"" << (*j).second.second + // << ""'"" << std::endl; + return ((*i).second.second == """"? 1 : -1); + } + + ++i; + ++j; + } + + if (lhs.num_sites() != rhs.num_sites()) + { + return (lhs.num_sites() < rhs.num_sites()? 1 : -1); + } + + ignores_.insert( + std::lower_bound(ignores_.begin(), ignores_.end(), pair_key), + pair_key); + i = lhs.begin(); + j = rhs.begin(); + while (i != lhs.end() && j != rhs.end()) + { + if ((*i).second.second != """" && (*i).second.second != """") + { + const std::vector& + pair1(connections_[(*i).second.second]); + const std::vector& + pair2(connections_[(*j).second.second]); + const site_type& target1( + (pair1[0].first == val1 && pair1[0].second == (*i).first)? + pair1[1] : pair1[0]); + const site_type& target2( + (pair2[0].first == val2 && pair2[0].second == (*j).first)? + pair2[1] : pair2[0]); + if (target1.second != target2.second) + { + ignores_.pop_back(); + return (target1.second < target2.second? 1 : -1); + } + + const int retval(compare(target1.first, target2.first)); + // std::cout << ""[0] "" << lhs.serial() << ""("" << val1 << "") vs "" + // << rhs.serial() << ""("" << val2 << "") -> "" << retval + // << std::endl; + if (retval != 0) + { + ignores_.pop_back(); + return retval; + } + } + + ++i; + ++j; + } + ignores_.pop_back(); + return 0; + } + + bool operator()(const index_type& val1, const index_type& val2) + { + // return val1 < val2; + ignores_.clear(); + return 0 < compare(val1, val2); + } + + void reorder_units( + std::vector& unit_indices, const unsigned int& idx, + unsigned int& stride) + { + if (unit_indices[idx] != root_.size()) + { + return; + } + + const UnitSpecies& usp(root_.at(idx)); + + unit_indices[idx] = stride; + ++stride; + + for (UnitSpecies::container_type::const_iterator i(usp.begin()); + i != usp.end(); ++i) + { + if ((*i).second.second == """" || is_wildcard((*i).second.second)) + { + continue; + } + + // const std::vector& + // pair((*connections_.find((*i).second.second)).second); + const std::vector& + pair(connections_[(*i).second.second]); + const species_structure::site_type& + tgt((pair[0].first == idx && pair[0].second == (*i).first)? + pair[1] : pair[0]); + + reorder_units(unit_indices, tgt.first, stride); + } + } + +protected: + + const std::vector root_; + connection_container_type connections_; + std::vector > ignores_; +}; + +// int compare_unit_species(const UnitSpecies& lhs, const UnitSpecies& rhs) +// { +// if (lhs.name() != rhs.name()) +// { +// return (lhs.name() < rhs.name() ? 1 : -1); +// } +// +// for (UnitSpecies::container_type::const_iterator i(lhs.begin()), j(rhs.begin()); +// i != lhs.end() && j != rhs.end(); ++i, ++j) +// { +// if ((*i).first != (*j).first) +// { +// return ((*i).first < (*j).first ? 1 : -1); +// } +// else if ((*i).second.first != (*j).second.first) +// { +// return ((*i).second.first < (*j).second.first ? 1 : -1); +// } +// else if (((*i).second.second == """") != ((*j).second.second == """")) +// { +// return ((*i).second.second == """" ? 1 : -1); +// } +// } +// +// if (lhs.num_sites() != rhs.num_sites()) +// { +// return (lhs.num_sites() < rhs.num_sites() ? 1 : -1); +// } +// return 0; +// } +// +// struct less_unit_species +// { +// bool operator()(const UnitSpecies& lhs, const UnitSpecies& rhs) +// { +// return compare_unit_species(lhs, rhs) > 0; +// } +// }; + +Species format_species(const Species& sp) +{ + // { + // std::vector res; + + // std::vector units = sp.units(); + // std::sort(units.begin(), units.end(), less_unit_species()); + + // species_formatter formatter(units); + // std::vector::difference_type start = 0; + // while (true) + // { + // std::vector permutation(units.size(), units.size()); + // species_formatter::size_type stride = formatter.sort(permutation, start, 0); + // res.push_back(formatter.collect(permutation)); + // std::vector::iterator start_it = permutation.begin(); + // std::advance(start_it, start); + // start = std::distance(permutation.begin(), std::find(start_it, permutation.end(), units.size())); + // if (start == units.size()) + // { + // break; + // } + // } + + // std::cout << ""BEFORE: "" << sp.serial() << std::endl; + // std::cout << ""AFTER: ""; + + // for (std::vector::const_iterator i = res.begin(); i != res.end(); ++i) + // { + // std::cout << "" "" << (*i).serial(); + // } + // std::cout << std::endl; + // } + + species_structure comp(sp); + const std::vector::size_type num_units = comp.units().size(); + + std::vector units; + for (species_structure::index_type i(0); i < num_units; ++i) + { + units.push_back(i); + } + + std::sort(units.begin(), units.end(), comp); + + std::vector + next(num_units, num_units); + unsigned int stride(0); + for (species_structure::index_type i(0); i < num_units; ++i) + { + const species_structure::index_type idx(units[i]); + comp.reorder_units(next, idx, stride); + } + for (unsigned int i(0); i < num_units; ++i) + { + units[next[i]] = i; + } + + Species newsp; + std::unordered_map cache; + stride = 1; + std::stringstream ss; + for (std::vector::const_iterator + i(units.begin()); i != units.end(); ++i) + { + UnitSpecies usp(sp.units().at(*i)); + for (UnitSpecies::container_type::size_type j(0); + j < static_cast(usp.num_sites()); ++j) + { + UnitSpecies::container_type::value_type& site(usp.at(j)); + if (site.second.second == """" || is_wildcard(site.second.second)) + { + continue; + } + + std::unordered_map::const_iterator + it(cache.find(site.second.second)); + if (it == cache.end()) + { + ss << stride; + cache.insert(std::make_pair(site.second.second, ss.str())); + site.second.second = ss.str(); + ++stride; + ss.clear(); + ss.str(""""); + } + else + { + site.second.second = (*it).second; + } + } + newsp.add_unit(usp); + } + return newsp; +} + +boost::optional::context_type> + rule_based_expression_matcher::match_unit_species( + const UnitSpecies& pttrn, + const UnitSpecies& usp, + const rule_based_expression_matcher::context_type& org) +{ + typedef rule_based_expression_matcher::context_type context_type; + + context_type ctx = org; + + if (is_wildcard(pttrn.name())) + { + if (is_pass_wildcard(pttrn.name())) + { + throw NotSupported( + ""A pass wildcard '_0' is not allowed to be a name of Species.""); + } + else if (is_named_wildcard(pttrn.name())) + { + context_type::variable_container_type::const_iterator + itr(ctx.globals.find(pttrn.name())); + if (itr == ctx.globals.end()) + { + ctx.globals[pttrn.name()] = usp.name(); + } + else if ((*itr).second != usp.name()) + { + return boost::none; + } + } + } + else if (pttrn.name() != usp.name()) + { + return boost::none; + } + + for (UnitSpecies::container_type::const_iterator j(pttrn.begin()); + j != pttrn.end(); ++j) + { + if (usp.has_site((*j).first)) + { + const UnitSpecies::site_type& site(usp.get_site((*j).first)); + + if ((*j).second.first != """") + { + if (site.first == """") + { + return boost::none; + } + else if (is_pass_wildcard((*j).second.first)) + { + throw NotSupported( + ""A pass wildcard '_0' is not allowed to be a state.""); + } + else if (is_unnamed_wildcard((*j).second.first)) + { + ; // do nothing + } + else if (is_named_wildcard((*j).second.first)) + { + context_type::variable_container_type::const_iterator + itr(ctx.globals.find((*j).second.first)); + if (itr == ctx.globals.end()) + { + ctx.globals[(*j).second.first] = site.first; + } + else if ((*itr).second != site.first) + { + return boost::none; + } + } + else if ((*j).second.first != site.first) + { + return boost::none; + } + } + + if (is_pass_wildcard((*j).second.second)) + { + ; // just skip checking + } + else if ((*j).second.second == """") + { + if (site.second != """") + { + return boost::none; + } + } + else + { + if (site.second == """") + { + return boost::none; + } + else if (is_unnamed_wildcard((*j).second.second)) + { + continue; + } + else if (is_named_wildcard((*j).second.second)) + { + throw NotSupported( + ""A named wildcard is not allowed to be a bond.""); + } + + context_type::variable_container_type::const_iterator + itr(ctx.locals.find((*j).second.second)); + if (itr == ctx.locals.end()) + { + ctx.locals[(*j).second.second] = site.second; + } + else if ((*itr).second != site.second) + { + return boost::none; + } + + } + } + else + { + return boost::none; + } + } + + return ctx; +} + +/* + * Apply a ReactionRule to the given set of reactants and return ReactionRules. + */ + +struct _ReactionRuleExpressionMatcher +{ + typedef rule_based_expression_matcher::context_type context_type; + typedef ReactionRule::reactant_container_type reactant_container_type; + + typedef struct + { + std::vector products; + std::vector::size_type> correspo; + std::vector::size_type> removed; + std::vector::size_type reserved; + } operation_type; + + typedef struct + { + std::vector units; + std::vector groups; + unsigned int num_groups; + } unit_group_type; +}; + +_ReactionRuleExpressionMatcher::operation_type compile_reaction_rule(const ReactionRule& pttrn) +{ + typedef std::vector::size_type size_type; + typedef std::vector::const_iterator const_iterator; + + _ReactionRuleExpressionMatcher::operation_type res = {}; + std::vector& products = res.products; + std::vector& correspo = res.correspo; + std::vector& removed = res.removed; + + // 1. Concatenate units of a pattern + + std::vector reactants; + for (ReactionRule::reactant_container_type::const_iterator + i(pttrn.reactants().begin()); i != pttrn.reactants().end(); ++i) + { + std::vector const units = (*i).units(); + reactants.reserve(reactants.size() + units.size()); + std::copy(units.begin(), units.end(), std::back_inserter(reactants)); + } + + res.reserved = reactants.size(); + + int product_bond_stride = 0; + for (ReactionRule::reactant_container_type::const_iterator + i(pttrn.products().begin()); i != pttrn.products().end(); ++i) + { + product_bond_stride += concatenate_units(products, (*i), product_bond_stride); + } + + // 2. Check correspondences between reactant and product units + + correspo.reserve(products.size()); + + { + size_type num_units(reactants.size()); + + size_type idx1 = 0; + for (const_iterator i(products.begin()); i != products.end(); ++i, ++idx1) + { + size_type idx2 = 0; + for (const_iterator j(reactants.begin()); j != reactants.end(); ++j, ++idx2) + { + if (is_correspondent(*i, *j)) + { + if (correspo.size() > idx1) + { + ; //WARN: multiple correspondence found + assert(false); // never get here + } + else if (std::find(correspo.begin(), correspo.end(), idx2) + != correspo.end()) + { + ; //WARN: multiple correspondence skipped + ; // The reactant matches is already assigned to the other product + } + else + { + correspo.push_back(idx2); + break; + } + } + } + + // If no reactant is found, create new one + if (correspo.size() == idx1) + { + correspo.push_back(num_units); + ++num_units; + } + } + } + + // List reactants removed after reacting + for (size_type i(0); i < reactants.size(); ++i) + { + if (std::find(correspo.begin(), correspo.end(), i) == correspo.end()) + { + removed.push_back(i); + } + } + + return res; +} + +_ReactionRuleExpressionMatcher::unit_group_type generate_units( + const _ReactionRuleExpressionMatcher::operation_type& operations, + const _ReactionRuleExpressionMatcher::context_type& ctx, + const ReactionRule::reactant_container_type& target, + const ReactionRule::policy_type& policy) +{ + typedef _ReactionRuleExpressionMatcher::context_type context_type; + typedef _ReactionRuleExpressionMatcher::unit_group_type unit_group_type; + typedef std::vector::size_type size_type; + + const std::vector& products = operations.products; + const std::vector& correspo = operations.correspo; + const std::vector& removed = operations.removed; + const size_type& reserved = operations.reserved; + + unit_group_type res = {}; + std::vector& units = res.units; + std::vector& groups = res.groups; + unsigned int& num_groups = res.num_groups; + + // 3. Concatenate units given as reactants + + // const context_type ctx(context()); + + int bond_stride = 0; + + //XXX: for (std::vector::const_iterator + //XXX: i(permutation_.begin()); i != permutation_.end(); ++i) + //XXX: { + //XXX: bond_stride += concatenate_units(units, target[*i], bond_stride); + //XXX: } + for (ReactionRule::reactant_container_type::const_iterator + i(target.begin()); i != target.end(); ++i) + { + bond_stride += concatenate_units(units, *i, bond_stride); + } + + // 4. Modify units + + std::unordered_map bond_cache; + + { + std::vector > priorities; + { + size_type next_idx = units.size(); + size_type idx = 0; + for (std::vector::const_iterator i(correspo.begin()); + i != correspo.end(); ++i, ++idx) + { + if ((*i) < reserved) + { + assert(ctx.iterators.size() > (*i)); + priorities.push_back(std::make_pair(ctx.iterators[(*i)], idx)); + } + else + { + priorities.push_back(std::make_pair(next_idx, idx)); + ++next_idx; + } + } + std::sort(priorities.begin(), priorities.end()); + } + + for (std::vector >::const_iterator + itr1(priorities.begin()); itr1 != priorities.end(); ++itr1) + { + const UnitSpecies& op = products[(*itr1).second]; + const size_type& tgt = (*itr1).first; + + if (tgt >= units.size()) + { + // 4-1. Create a new unit + assert(tgt == units.size()); + // tgt = units.size(); + units.push_back(op); + if (is_named_wildcard(op.name())) + { + context_type::variable_container_type::const_iterator + itr(ctx.globals.find(op.name())); + if (itr == ctx.globals.end()) + { + std::stringstream message; + message << ""A named wildcard ["" << op.name() << ""] cannot be resolved.""; + throw IllegalState(message.str()); + } + else + { + units.back().set_name((*itr).second); + } + } + } + // else + // { + // tgt = ctx.iterators[idx2]; + // } + + for (UnitSpecies::container_type::const_iterator i(op.begin()); + i != op.end(); ++i) + { + UnitSpecies::container_type::value_type& + site(units[tgt].at((*i).first)); + + // 4-2. Update sites + if ((*i).second.first == """") + { + ; // do nothing + } + else if (is_wildcard((*i).second.first)) + { + if ((*i).second.first.size() != 1) + { + context_type::variable_container_type::const_iterator + itr(ctx.globals.find((*i).second.first)); + if (itr == ctx.globals.end()) + { + std::stringstream message; + message << ""An invalid global name ["" << (*i).second.first << ""] was given.""; + throw IllegalState(message.str()); + } + else + { + site.second.first = (*itr).second; + } + } + } + else + { + site.second.first = (*i).second.first; + } + + // 4-3. Update bonds + if ((*i).second.second == """") + { + // Just cut the bond + site.second.second = """"; + } + else if (is_wildcard((*i).second.second)) + { + if (is_named_wildcard((*i).second.second)) + { + std::stringstream message; + message << ""A named wildcard ["" << (*i).second.second << ""cannot be a bond."" + << "" Only a unnamed wildcard is accepted here.""; + throw IllegalState(message.str()); + } + + ; // do nothing + } + else + { + // Make a new bond + std::unordered_map::const_iterator + itr(bond_cache.find((*i).second.second)); + if (itr != bond_cache.end()) + { + site.second.second = (*itr).second; + } + else + { + ++bond_stride; + site.second.second = itos(bond_stride); + bond_cache.insert(std::make_pair((*i).second.second, site.second.second)); + } + } + } + } + } + + // 5. Remove units deleted + + if (removed.size() > 0) + { + for (std::vector::size_type>::const_iterator + i(removed.begin()); i != removed.end(); ++i) + { + units[ctx.iterators[(*i)]] = UnitSpecies(); + } + } + + // The following is originally in group_units() + + // 6. Check connections between bonds and units + + std::unordered_map> bondinfo; + const unsigned int done = units.size(); + + std::vector::size_type> > connections; + connections.resize(units.size()); + + { + unsigned int idx = 0; + for (std::vector::const_iterator i(units.begin()); + i != units.end(); ++i, ++idx) + { + for (UnitSpecies::container_type::const_iterator j((*i).begin()); + j != (*i).end(); ++j) + { + const std::string bond((*j).second.second); + if (bond == """") + { + continue; + } + else if (is_wildcard(bond)) + { + std::stringstream ss; + ss << ""A bond in a product is a wildcard ["" + << (*i).name() << ""("" << (*j).first << ""^"" << bond << "")].""; + throw IllegalState(ss.str()); + } + + std::unordered_map>::iterator + itr(bondinfo.find(bond)); + if (itr == bondinfo.end()) + { + bondinfo[bond] = std::make_pair((*j).first, idx); + } + else + { + const unsigned int another = (*itr).second.second; + if (another == done) + { + std::stringstream ss; + ss << ""A bond in a product is multiply connected ["" + << (*i).name() << ""("" << (*j).first << ""^"" << bond << "")].""; + throw IllegalState(ss.str()); + } + + connections[idx].push_back(another); + connections[another].push_back(idx); + bondinfo[bond].second = done; // This means the bond is already assigned. + } + } + } + } + + // const ReactionRule::policy_type& policy(pttrn.policy()); + + if ((policy & ReactionRule::POLICY_STRICT) + && !(policy & (ReactionRule::POLICY_DESTROY | ReactionRule::POLICY_IMPLICIT))) + { + for (std::unordered_map>::const_iterator + i(bondinfo.begin()); i != bondinfo.end(); ++i) + { + if ((*i).second.second != done) + { + std::stringstream ss; + ss << ""A bond in a product is not resolved ["" << (*i).first << ""].""; + { + Species sp; + for (std::vector::const_iterator j(units.begin()); + j != units.end(); ++j) + { + sp.add_unit((*j)); + } + ss << "" "" << sp.serial(); + } + throw IllegalState(ss.str()); + } + } + } + + // 7. Group units based on the connections + + const unsigned int notyet = units.size(); + groups.resize(units.size(), notyet); + + for (unsigned int idx(0); idx != units.size(); ++idx) + { + if (units[idx] == UnitSpecies()) + { + continue; // A removed unit + } + + // std::cout << idx << "" connects with ""; + // for (std::vector::size_type>::const_iterator + // i(connections[idx].begin()); i != connections[idx].end(); ++i) + // { + // std::cout << *i; + // } + // std::cout << std::endl; + + num_groups = tag_units( + groups, num_groups, idx, connections, notyet); + } + + assert(num_groups <= notyet); + + // 8. Resolve open bonds based on the policy + + if (policy & ReactionRule::POLICY_IMPLICIT) + { + for (std::vector::iterator i(units.begin()); + i != units.end(); ++i) + { + for (UnitSpecies::container_type::size_type j(0); + static_cast(j) != (*i).num_sites(); ++j) + { + UnitSpecies::container_type::value_type& site((*i).at(j)); + const std::string bond(site.second.second); + if (bond != """" && !is_wildcard(bond) && bondinfo[bond].second != done) + { + site.second.second = """"; + } + } + } + } + + if (policy & ReactionRule::POLICY_DESTROY) + { + for (std::unordered_map>::const_iterator + i(bondinfo.begin()); i != bondinfo.end(); ++i) + { + if ((*i).second.second != done && units[(*i).second.second] != UnitSpecies()) + { + const unsigned int group_id = groups[(*i).second.second]; + + // assert(num_groups > 0); + // --num_groups; + std::vector::iterator j1(groups.begin()); + for (std::vector::iterator j2(units.begin()); + j2 != units.end(); ++j1, ++j2) + { + if ((*j1) == group_id) + { + (*j2) = UnitSpecies(); + // (*j1) = notyet; + } + } + } + } + } + + return res; +} + +std::vector group_units( + const std::vector& units, + const std::vector& groups, + const unsigned int num_groups) +{ + // 8. Divide units into Species + + std::vector products; + products.resize(num_groups); + + // { + // std::vector::size_type idx = 0; + // for (std::vector::iterator i(units.begin()); + // i != units.end(); ++i; ++idx) + // { + // products[groups[idx]].add_unit(*i); + // } + // } + + for (unsigned int idx(0); idx != num_groups; ++idx) + { + std::unordered_map new_bonds; + unsigned int stride(1); + + for (std::vector::const_iterator + i(groups.begin()); i != groups.end(); ++i) + { + if (idx != *i) + { + continue; + } + + UnitSpecies usp(units[std::distance(groups.begin(), i)]); //XXX: copy + + if (usp == UnitSpecies()) + { + continue; + } + + for (UnitSpecies::container_type::size_type j(0); + static_cast(j) != usp.num_sites(); ++j) + { + UnitSpecies::container_type::value_type& + site(usp.at(j)); + const std::string bond(site.second.second); + if (bond == """" || is_wildcard(bond)) + { + continue; + } + + std::unordered_map::const_iterator + itr(new_bonds.find(bond)); + if (itr == new_bonds.end()) + { + const std::string new_bond(itos(stride)); + ++stride; + new_bonds[bond] = new_bond; + site.second.second = new_bond; + } + else + { + site.second.second = (*itr).second; + } + } + + products[idx].add_unit(usp); + } + + // products[idx] = format_species(products[idx]); + } + + products.erase(std::remove(products.begin(), products.end(), Species()), products.end()); + + return products; +} + +}; // context + +std::vector generate_reaction_rules( + const ReactionRule& pttrn, + const ReactionRule::reactant_container_type& reactants) +{ + typedef context::_ReactionRuleExpressionMatcher::operation_type operation_type; + typedef context::_ReactionRuleExpressionMatcher::unit_group_type unit_group_type; + typedef context::rule_based_expression_matcher >::context_type context_type; + typedef std::vector return_type; + + if (pttrn.reactants().size() == 0) + { + return return_type( + 1, ReactionRule(reactants, pttrn.products(), pttrn.k())); // Zeroth-order reactions + } + + std::vector > candidates; + const operation_type op = context::compile_reaction_rule(pttrn); + + return_type reactions; + context::rule_based_expression_matcher > matcher(pttrn.reactants()); + for (boost::optional ctx = matcher.match(reactants); ctx; ctx = matcher.next()) + { + const unit_group_type _res + = context::generate_units(op, (*ctx), reactants, pttrn.policy()); + + std::vector >::iterator + i(std::find(candidates.begin(), candidates.end(), _res.units)); + if (i != candidates.end()) + { + ; // (*i).set_k((*i).k() + rr.k()); + } + else + { + candidates.push_back(_res.units); + reactions.push_back( + ReactionRule( + reactants, + context::group_units(_res.units, _res.groups, _res.num_groups), + pttrn.k())); + } + } + return reactions; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/TriangleView.hpp",".hpp","6100","238","#ifndef ECELL_CORE_TRIANGLE_VIEW +#define ECELL_CORE_TRIANGLE_VIEW + +#include ""Shape.hpp"" +#include ""geometry.hpp"" +#include ""exceptions.hpp"" + +namespace ecell4 +{ + +struct TriangleView : public Shape +{ + public: + + TriangleView(Real3& a, Real3& b, Real3& c) + { + this->vertices_[0] = &a; + this->vertices_[1] = &b; + this->vertices_[2] = &c; + } + + TriangleView(TriangleView const& rhs) + { + this->vertices_[0] = rhs.vertices_[0]; + this->vertices_[1] = rhs.vertices_[1]; + this->vertices_[2] = rhs.vertices_[2]; + } + TriangleView& operator=(TriangleView const& rhs) + { + this->vertices_[0] = rhs.vertices_[0]; + this->vertices_[1] = rhs.vertices_[1]; + this->vertices_[2] = rhs.vertices_[2]; + return *this; + } + + Real3 normal() const + { + const Real3 n = cross_product(this->edges(0), this->edges(2) * (-1)); + return (n * (1. / length(n))); + } + Real3 represent() const + { + const Real3 e = this->edges(0); + return e / length(e); + } + + Real3& vertex_at(const std::size_t i) const + { + return *(vertices_.at(i)); + } + Real3& vertices(const std::size_t i) const + { + return *(vertices_[i]); + } + + Real3 edge_at(const std::size_t i) const + { + return *(vertices_.at(i==2?0:i+1)) - *(vertices_.at(i)); + } + Real3 edges(const std::size_t i) const + { + return *(vertices_[i==2?0:i+1]) - *(vertices_[i]); + } + + Real length_of_edge_at(const std::size_t i) const + { + return length(edge_at(i)); + } + + Real angle_at(const std::size_t i) const + { + return calc_angle(this->edges(i), this->edges(i==0?2:i-1) * -1.0); + } + + Real area() const + { + return 0.5 * length(cross_product(this->edges(0), this->edges(2) * (-1.0))); + } + + // shape + dimension_kind dimension() const + { + return TWO; + } + Real is_inside(const Real3& coord) const + { + throw NotImplemented(""TriangleView::is_inside(coord)""); + } + Real3 draw_position(std::shared_ptr& rng) const + { + Real a1 = rng->uniform(0.0, 1.0); + Real a2 = rng->uniform(0.0, 1.0); + if(a1 + a2 > 1.0) + { + a1 = 1.0 - a1; + a2 = 1.0 - a2; + } + return *(this->vertices_[0]) + this->edges(0) * a1 - this->edges(2) * a2; + } + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Triangle::test_AABB(l, u)""); + } + void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + throw NotImplemented(""Triangle::bounding_box(edge_length, lower, upper)""); + } + + std::array const& get_vertices() const {return vertices_;} + + private: + std::array vertices_; +}; + +struct TriangleConstView : public Shape +{ + public: + + TriangleConstView(const Real3& a, const Real3& b, const Real3& c) + { + this->vertices_[0] = &a; + this->vertices_[1] = &b; + this->vertices_[2] = &c; + } + + TriangleConstView(TriangleConstView const& rhs) + { + this->vertices_[0] = rhs.vertices_[0]; + this->vertices_[1] = rhs.vertices_[1]; + this->vertices_[2] = rhs.vertices_[2]; + } + TriangleConstView& operator=(TriangleConstView const& rhs) + { + this->vertices_[0] = rhs.vertices_[0]; + this->vertices_[1] = rhs.vertices_[1]; + this->vertices_[2] = rhs.vertices_[2]; + return *this; + } + TriangleConstView(TriangleView const& rhs) + { + this->vertices_[0] = rhs.get_vertices()[0]; + this->vertices_[1] = rhs.get_vertices()[1]; + this->vertices_[2] = rhs.get_vertices()[2]; + } + TriangleConstView& operator=(TriangleView const& rhs) + { + this->vertices_[0] = rhs.get_vertices()[0]; + this->vertices_[1] = rhs.get_vertices()[1]; + this->vertices_[2] = rhs.get_vertices()[2]; + return *this; + } + + Real3 normal() const + { + const Real3 n = cross_product(this->edges(0), this->edges(2) * (-1)); + return (n * (1. / length(n))); + } + Real3 represent() const + { + const Real3 e = this->edges(0); + return e / length(e); + } + + Real3 const& vertex_at(const std::size_t i) const + { + return *(vertices_.at(i)); + } + Real3 const& vertices(const std::size_t i) const + { + return *(vertices_[i]); + } + + Real3 edge_at(const std::size_t i) const + { + return *(vertices_.at(i==2?0:i+1)) - *(vertices_.at(i)); + } + Real3 edges(const std::size_t i) const + { + return *(vertices_[i==2?0:i+1]) - *(vertices_[i]); + } + + Real length_of_edge_at(const std::size_t i) const + { + return length(edge_at(i)); + } + + Real angle_at(const std::size_t i) const + { + return calc_angle(this->edges(i), this->edges(i==0?2:i-1) * -1.0); + } + + Real area() const + { + return 0.5 * length(cross_product(this->edges(0), this->edges(2) * (-1.0))); + } + + // shape + dimension_kind dimension() const + { + return TWO; + } + Real is_inside(const Real3& coord) const + { + throw NotImplemented(""TriangleView::is_inside(coord)""); + } + Real3 draw_position(std::shared_ptr& rng) const + { + Real a1 = rng->uniform(0.0, 1.0); + Real a2 = rng->uniform(0.0, 1.0); + if(a1 + a2 > 1.0) + { + a1 = 1.0 - a1; + a2 = 1.0 - a2; + } + return *(this->vertices_[0]) + this->edges(0) * a1 - this->edges(2) * a2; + } + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Triangle::test_AABB(l, u)""); + } + void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + throw NotImplemented(""Triangle::bounding_box(edge_length, lower, upper)""); + } + + std::array const& get_vertices() const {return vertices_;} + + private: + std::array vertices_; +}; + + +} // ecell4 + +#endif /*ECELL_CORE_TRIANGLE_VIEW*/ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/RandomNumberGenerator.cpp",".cpp","3124","121","#include +#include + +#include ""RandomNumberGenerator.hpp"" + +#ifdef WITH_HDF5 +#include ""extras.hpp"" +#endif + +namespace ecell4 +{ + +#ifdef WITH_HDF5 +void GSLRandomNumberGenerator::save(H5::H5Location* root) const +{ + using namespace H5; + + std::unique_ptr optype(new DataType(H5T_OPAQUE, 1)); + hsize_t bufsize(gsl_rng_size(rng_.get())); + DataSpace dataspace(1, &bufsize); + optype->setTag(""GSLRandomNumberGenerator state type""); + std::unique_ptr dataset( + new DataSet(root->createDataSet(""rng"", *optype, dataspace))); + dataset->write((unsigned char*)(gsl_rng_state(rng_.get())), *optype); +} + +void GSLRandomNumberGenerator::load(const H5::H5Location& root) +{ + using namespace H5; + + const DataSet dataset(DataSet(root.openDataSet(""rng""))); + // size_t bufsize(gsl_rng_size(rng_.get())); + std::unique_ptr optype(new DataType(H5T_OPAQUE, 1)); + optype->setTag(""GSLRandomNumberGenerator state type""); + unsigned char* state = (unsigned char*)(gsl_rng_state(rng_.get())); + dataset.read(state, *optype); +} + +void GSLRandomNumberGenerator::save(const std::string& filename) const +{ + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + this->save(fout.get()); + extras::save_version_information(fout.get(), std::string(""ecell4-gsl_number_generator-"") + std::string(VERSION_INFO)); +} + +void GSLRandomNumberGenerator::load(const std::string& filename) +{ + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + this->load(*fin); +} +#endif + +Real GSLRandomNumberGenerator::random() +{ + return gsl_rng_uniform(rng_.get()); +} + +Real GSLRandomNumberGenerator::uniform(Real min, Real max) +{ + return gsl_rng_uniform(rng_.get()) * (max - min) + min; +} + +Integer GSLRandomNumberGenerator::uniform_int(Integer min, Integer max) +{ + if (max < min) + { + throw std::invalid_argument( + ""the max value must be larger than the min value.""); + } + + const unsigned long int n(max - min + 1); + const unsigned long int range(rng_->type->max - rng_->type->min); + + if (n <= range) + { + return gsl_rng_uniform_int(rng_.get(), n) + min; + } + else + { + const Integer m((max - min) / range); + Integer k; + do + { + k = min + gsl_rng_uniform_int(rng_.get(), range) + + range * gsl_rng_uniform_int(rng_.get(), m + 1); + } while (k > max); + return k; + } +} + +Real GSLRandomNumberGenerator::gaussian(Real sigma, Real mean) +{ + return gsl_ran_gaussian(rng_.get(), sigma) + mean; +} + +Integer GSLRandomNumberGenerator::binomial(Real p, Integer n) +{ + return gsl_ran_binomial(rng_.get(), p, n); +} + +Real3 GSLRandomNumberGenerator::direction3d(Real length) +{ + double x, y, z; + gsl_ran_dir_3d(rng_.get(), &x, &y, &z); + return Real3(x * length, y * length, z * length); +} + +void GSLRandomNumberGenerator::seed(Integer val) +{ + gsl_rng_set(rng_.get(), val); +} + +void GSLRandomNumberGenerator::seed() +{ + gsl_rng_set(rng_.get(), unsigned(std::time(0))); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/converter.hpp",".hpp","782","37","#ifndef ECELL4_UTIL_CONVERTER +#define ECELL4_UTIL_CONVERTER +#include + +namespace ecell4 +{ +namespace utils +{ + +template +struct pair_first_element_converter +{ + typedef T_convert result_type; + typedef std::pair element_type; + + result_type operator()(const element_type& v) const + { + return result_type(v.first); + } +}; + +template +struct pair_second_element_converter +{ + typedef T_convert result_type; + typedef std::pair element_type; + + result_type operator()(const element_type& v) const + { + return result_type(v.second); + } +}; + +} // utils +} // ecell4 +#endif// ECELL4_UTIL_CONVERTER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/geometry.cpp",".cpp","648","23","#include ""geometry.hpp"" +#include +#include + +namespace ecell4 +{ + +Real3 rotate(const Real angle, const Real3& axis, const Real3& target) +{ + typedef boost::math::quaternion Quaternion; + const Real cos_t(std::cos(angle * 0.5)); + const Real sin_t(std::sin(angle * 0.5)); + const Real sin_n(sin_t / length(axis)); + + const Quaternion Q(cos_t, axis[0] * sin_n, axis[1] * sin_n, axis[2] * sin_n); + const Quaternion P(0e0, target[0], target[1], target[2]); + const Quaternion S(Q * P * boost::math::conj(Q)); + + return Real3(S.R_component_2(), S.R_component_3(), S.R_component_4()); +} + +}//ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpace.cpp",".cpp","6374","234","#include +#include + +#include ""exceptions.hpp"" +#include ""Context.hpp"" +#include ""comparators.hpp"" +#include ""ParticleSpace.hpp"" + + +namespace ecell4 +{ + +Integer ParticleSpaceVectorImpl::num_particles() const +{ + return static_cast(particles_.size()); +} + +Integer ParticleSpaceVectorImpl::num_particles(const Species& sp) const +{ + return static_cast(list_particles(sp).size()); +} + +Integer ParticleSpaceVectorImpl::num_molecules(const Species& sp) const +{ + Integer retval(0); + SpeciesExpressionMatcher sexp(sp); + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + retval += sexp.count((*i).second.species()); + } + return retval; +} + +Integer ParticleSpaceVectorImpl::num_molecules_exact(const Species& sp) const +{ + return num_particles_exact(sp); +} + +Integer ParticleSpaceVectorImpl::num_particles_exact(const Species& sp) const +{ + return static_cast(list_particles_exact(sp).size()); +} + +bool ParticleSpaceVectorImpl::has_particle(const ParticleID& pid) const +{ + particle_map_type::const_iterator i(index_map_.find(pid)); + return (i != index_map_.end()); +} + +/** + * update or add a particle. + * @return true if adding a new particle + */ +bool ParticleSpaceVectorImpl::update_particle( + const ParticleID& pid, const Particle& p) +{ + particle_map_type::const_iterator i(index_map_.find(pid)); + if (i == index_map_.end()) + { + particle_container_type::size_type idx(particles_.size()); + index_map_[pid] = idx; + particles_.push_back(std::make_pair(pid, p)); + return true; + } + else + { + particles_[(*i).second] = std::make_pair(pid, p); + return false; + } +} + +void ParticleSpaceVectorImpl::remove_particle(const ParticleID& pid) +{ + particle_map_type::const_iterator i(index_map_.find(pid)); + if (i == index_map_.end()) + { + throw NotFound(""particle not found""); + } + + particle_map_type::mapped_type + idx((*i).second),last_idx(particles_.size() - 1); + if (idx != last_idx) + { + const std::pair& last(particles_[last_idx]); + particles_[idx] = last; + index_map_[last.first] = idx; + } + + particles_.pop_back(); + index_map_.erase((*i).first); +} + +std::pair ParticleSpaceVectorImpl::get_particle( + const ParticleID& pid) const +{ + particle_map_type::const_iterator i(index_map_.find(pid)); + if (i == index_map_.end()) + { + throw NotFound(""particle not found""); + } + + return particles_[(*i).second]; +} + +std::vector > +ParticleSpaceVectorImpl::list_particles() const +{ + return particles_; +} + +std::vector > +ParticleSpaceVectorImpl::list_particles(const Species& sp) const +{ + std::vector > retval; + SpeciesExpressionMatcher sexp(sp); + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + if (sexp.match((*i).second.species())) + { + retval.push_back(*i); + } + } + return retval; +} + +std::vector > +ParticleSpaceVectorImpl::list_particles_exact(const Species& sp) const +{ + std::vector > retval; + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + if ((*i).second.species() == sp) + { + retval.push_back(*i); + } + } + + return retval; +} + +std::vector, Real> > +ParticleSpaceVectorImpl::list_particles_within_radius( + const Real3& pos, const Real& radius) const +{ + std::vector, Real> > retval; + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + const Real dist(distance((*i).second.position(), pos) - (*i).second.radius()); + if (dist <= radius) + { + retval.push_back(std::make_pair(*i, dist)); + } + } + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>()); + return retval; +} + +std::vector, Real> > +ParticleSpaceVectorImpl::list_particles_within_radius( + const Real3& pos, const Real& radius, const ParticleID& ignore) const +{ + std::vector, Real> > retval; + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + const Real dist(distance((*i).second.position(), pos) - (*i).second.radius()); + if (dist <= radius) + { + if ((*i).first != ignore) + { + retval.push_back(std::make_pair(*i, dist)); + } + } + } + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>()); + return retval; +} + +std::vector, Real> > +ParticleSpaceVectorImpl::list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const +{ + std::vector, Real> > retval; + + for (particle_container_type::const_iterator i(particles_.begin()); + i != particles_.end(); ++i) + { + const Real dist(distance((*i).second.position(), pos) - (*i).second.radius()); + if (dist <= radius) + { + if ((*i).first != ignore1 && (*i).first != ignore2) + { + retval.push_back(std::make_pair(*i, dist)); + } + } + } + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>()); + return retval; +} + +void ParticleSpaceVectorImpl::reset(const Real3& edge_lengths) +{ + base_type::t_ = 0.0; + particles_.clear(); + index_map_.clear(); + + for (Real3::size_type dim(0); dim < 3; ++dim) + { + if (edge_lengths[dim] <= 0) + { + throw std::invalid_argument(""the edge length must be positive.""); + } + } + + edge_lengths_ = edge_lengths; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Barycentric.hpp",".hpp","3011","109","#ifndef ECELL_BARYCENTRIC_HPP +#define ECELL_BARYCENTRIC_HPP +#include + +namespace ecell4 +{ + +struct Barycentric +{ + typedef Real value_type; + typedef std::size_t size_type; + typedef size_type index_type; + typedef std::array container_type; + + Barycentric(){} + ~Barycentric(){} + + Barycentric(const Real a, const Real b, const Real c) throw() + { + val[0] = a; + val[1] = b; + val[2] = c; + } + Barycentric(const Barycentric& rhs) throw() + { + val[0] = rhs.val[0]; + val[1] = rhs.val[1]; + val[2] = rhs.val[2]; + } + Barycentric& operator=(const Barycentric& b) throw() + { + val[0] = b.val[0]; + val[1] = b.val[1]; + val[2] = b.val[2]; + return *this; + } + + Real operator[](const index_type i) const throw() {return val[i];} + Real& operator[](const index_type i) throw() {return val[i];} + Real at(const index_type i) const {return val.at(i);} + Real& at(const index_type i) {return val.at(i);} + + private: + container_type val; +}; + +template +inline std::basic_ostream& +operator<<(std::basic_ostream& os, const Barycentric& b) +{ + os << b[0] << "", "" << b[1] << "", "" << b[2]; + return os; +} + +inline Barycentric +operator+(const Barycentric& lhs, const Barycentric& rhs) throw() +{ + return Barycentric(lhs[0] + rhs[0], lhs[1] + rhs[1], lhs[2] + rhs[2]); +} + +inline Barycentric +operator-(const Barycentric& lhs, const Barycentric& rhs) throw() +{ + return Barycentric(lhs[0] - rhs[0], lhs[1] - rhs[1], lhs[2] - rhs[2]); +} +inline Barycentric +operator*(const Barycentric& lhs, const Real rhs) throw() +{ + return Barycentric(lhs[0] * rhs, lhs[1] * rhs, lhs[2] * rhs); +} + +// utility functions... + +inline bool on_plane(const Barycentric& bary, const Real tol = 1e-10) throw() +{ + return std::abs(bary[0] + bary[1] + bary[2] - 1.0) < tol; +} + +inline bool is_inside(const Barycentric& bary) throw() +{ + return on_plane(bary) && (0. <= bary[0] && bary[0] <= 1.0) && + (0. <= bary[1] && bary[1] <= 1.0) && + (0. <= bary[2] && bary[2] <= 1.0); +} + +inline bool is_inside(const Barycentric& bary, const Real tolerance) throw() +{ + return on_plane(bary) && + (0.0 - tolerance <= bary[0] && bary[0] <= 1.0 + tolerance) && + (0.0 - tolerance <= bary[1] && bary[1] <= 1.0 + tolerance) && + (0.0 - tolerance <= bary[2] && bary[2] <= 1.0 + tolerance); +} + +std::pair +first_cross_edge(const Barycentric& pos, const Barycentric& disp); + +Barycentric force_put_inside(const Barycentric& bary); + +Barycentric to_barycentric(const Real3& pos, const Triangle& face); + +inline Real3 to_absolute(const Barycentric& bary, const Triangle& tri) throw() +{ + return tri.vertex_at(0) * bary[0] + tri.vertex_at(1) * bary[1] + + tri.vertex_at(2) * bary[2]; +} + +}// ecell4 +#endif // ECELL_BARYCENTRIC_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/collision.hpp",".hpp","5903","201","#ifndef ECELL4_COLLISION_HPP +#define ECELL4_COLLISION_HPP + +#include ""types.hpp"" +#include ""Real3.hpp"" + +#include ""AABB.hpp"" +#include ""Cylinder.hpp"" +#include ""PlanarSurface.hpp"" +#include ""Sphere.hpp"" +#include ""Rod.hpp"" +#include ""Circle.hpp"" +#include ""Triangle.hpp"" +#include ""Cone.hpp"" +#include ""Barycentric.hpp"" + + +namespace ecell4 +{ + +namespace collision +{ + +inline Real clamp(const Real n, const Real min, const Real max) +{ + if (n < min) + { + return min; + } + else if (n > max) + { + return max; + } + return n; +} + +Real distance_sq_point_AABB(const Real3& pos, const AABB& b); +Real farthest_distance_sq_point_AABB(const Real3& pos, const AABB& b); +Real distance_point_cylinder(const Real3& pos, const Cylinder& c); +Real distance_point_capsule(const Real3& pos, const Rod& r); + +inline Real distance_sq_point_cylinder(const Real3& pos, const Cylinder& c) +{ + const Real L(distance_point_cylinder(pos, c)); + return L * L; +} + +Real closest_point_segment_segment( + const Real3& p1, const Real3& q1, + const Real3& p2, const Real3& q2, + Real& s, Real& t, Real3& c1, Real3& c2); + +bool test_AABB_AABB( + const Real3& l1, const Real3& u1, + const Real3& l2, const Real3& u2); + +inline bool test_AABB_AABB(const AABB& b1, const AABB& b2) +{ + return test_AABB_AABB(b1.lower(), b1.upper(), b2.lower(), b2.upper()); +} + +bool test_segment_AABB( + const Real3& p0, const Real3& p1, const Real3& lower, const Real3& upper); + +inline bool test_segment_AABB( + const Real3& p0, const Real3& p1, const AABB& b) +{ + return test_segment_AABB(p0, p1, b.lower(), b.upper()); +} + +bool test_AABB_plane(const AABB& b, const PlanarSurface& p); +bool test_shell_AABB(const SphericalSurface& s, const AABB& b); + +inline bool test_shell_AABB(const SphericalSurface& s, const Real3& l, const Real3& u) +{ + return test_shell_AABB(s, AABB(l, u)); +} + +bool test_sphere_AABB(const Sphere& s, const AABB& b); + +inline bool test_sphere_AABB(const Sphere& s, const Real3& l, const Real3& u) +{ + return test_sphere_AABB(s, AABB(l, u)); +} + +bool intersect_ray_AABB( + const Real3& p, const Real3& d, const Real3& lower, const Real3& upper, + Real& tmin, Real3& q); + +inline bool intersect_ray_AABB( + const Real3& p, const Real3& d, const AABB& b, + Real& tmin, Real3& q) +{ + return intersect_ray_AABB(p, d, b.lower(), b.upper(), tmin, q); +} + +bool intersect_segment_capsule( + const Real3& p1, const Real3& q1, + const Real3& p2, const Real3& q2, + const Real& radius, Real& s); + +bool intersect_moving_sphere_AABB( + const Sphere& s, const Real3& d, const AABB& b, Real& t); + +/* ------ 2D stuff ------ */ + +//XXX PROPOSAL: +// define struct Ray and Segment as one-dimensional Shape +// and use template specialization like +// - distance_sq +// - test +// - intersect + +Real3 closest_point_point_triangle(const Real3&, const Triangle&); +Real3 closest_point_point_circle(const Real3&, const Circle&); +Real3 closest_point_point_cone(const Real3&, const Cone&); + +inline Real distance_sq_point_triangle(const Real3& p, const Triangle& t) +{ + return length_sq(p - closest_point_point_triangle(p, t)); +} +inline Real distance_sq_point_circle(const Real3& p, const Circle& c) +{ + return length_sq(p - closest_point_point_circle(p, c)); +} +inline Real distance_sq_point_cone(const Real3& p, const Cone& c) +{ + return length_sq(p - closest_point_point_cone(p, c)); +} + +inline Real distance_sq_sphere_triangle(const Sphere& s, const Triangle& t) +{ + return distance_sq_point_triangle(s.center(), t) - s.radius(); +} +inline Real distance_sq_sphere_circle(const Sphere& s, const Circle& c) +{ + return distance_sq_point_circle(s.center(), c) - s.radius(); +} +inline Real distance_sq_sphere_cone(const Sphere& s, const Cone& c) +{ + return distance_sq_point_cone(s.center(), c) - s.radius(); +} + +inline bool test_sphere_triangle(const Sphere& s, const Triangle& t) +{ + return distance_sq_sphere_triangle(s, t) <= s.radius() * s.radius(); +} +inline bool test_sphere_circle(const Sphere& s, const Circle& c) +{ + return distance_sq_sphere_circle(s, c) <= s.radius() * s.radius(); +} +inline bool test_sphere_cone(const Sphere& s, const Cone& c) +{ + return distance_sq_sphere_cone(s, c) <= s.radius() * s.radius(); +} + +inline Real distance_sphere_triangle(const Sphere& s, const Triangle& t) +{ + return std::sqrt(distance_sq_sphere_triangle(s, t)); +} +inline Real distance_sphere_circle( const Sphere& s, const Circle& c) +{ + return std::sqrt(distance_sq_sphere_circle(s, c)); +} +inline Real distance_sphere_cone( const Sphere& s, const Cone& c) +{ + return std::sqrt(distance_sq_sphere_cone(s, c)); +} + +inline Real distance_point_triangle(const Real3& p, const Triangle& t) +{ + return std::sqrt(distance_sq_point_triangle(p, t)); +} +inline Real distance_point_circle( const Real3& p, const Circle& c) +{ + return std::sqrt(distance_sq_point_circle(p, c)); +} +inline Real distance_point_cone( const Real3& p, const Cone& c) +{ + return std::sqrt(distance_sq_point_cone(p, c)); +} + +bool intersect_segment_triangle(const Real3& p, const Real3& q, + const Triangle& t, Barycentric& b, Real& s); +bool intersect_segment_circle(const Real3& p, const Real3& q, + const Circle& c, Real& s); +bool intersect_segment_cone(const Real3& p, const Real3& q, + const Cone& c, Real& s); +bool intersect_ray_triangle(const Real3& pos, const Real3& disp, + const Triangle& t, Barycentric& b, Real3& q); +bool intersect_ray_circle(const Real3& pos, const Real3& disp, + const Circle& c, Real& t, Real3& q); +bool intersect_ray_cone(const Real3& pos, const Real3& disp, + const Cone& c, Real& t, Real3& q); + +} // collision + +} // ecell4 + +#endif /* ECELL4_COLLISION_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpaceCellListImpl.hpp",".hpp","15655","508","#ifndef ECELL4_PARTICLE_SPACE_CELL_LIST_IMPL_HPP +#define ECELL4_PARTICLE_SPACE_CELL_LIST_IMPL_HPP + +#include +#include +#include + +#include ""ParticleSpace.hpp"" + +#ifdef WITH_HDF5 +#include ""ParticleSpaceHDF5Writer.hpp"" +#endif + +#include ""Integer3.hpp"" + + +namespace ecell4 +{ + +class ParticleSpaceCellListImpl + : public ParticleSpace +{ +public: + + typedef ParticleSpace base_type; + typedef ParticleSpace::particle_container_type particle_container_type; + + typedef std::unordered_map + key_to_value_map_type; + + typedef std::set particle_id_set; + typedef std::map per_species_particle_id_set; + + typedef std::vector cell_type; // sorted + typedef boost::multi_array matrix_type; + typedef std::array cell_index_type; + typedef std::array cell_offset_type; + +public: + + ParticleSpaceCellListImpl(const Real3& edge_lengths) + : base_type(), edge_lengths_(edge_lengths), matrix_(boost::extents[3][3][3]) + { + cell_sizes_[0] = edge_lengths_[0] / matrix_.shape()[0]; + cell_sizes_[1] = edge_lengths_[1] / matrix_.shape()[1]; + cell_sizes_[2] = edge_lengths_[2] / matrix_.shape()[2]; + } + + ParticleSpaceCellListImpl( + const Real3& edge_lengths, const Integer3& matrix_sizes) + : base_type(), edge_lengths_(edge_lengths), + matrix_(boost::extents[matrix_sizes.col][matrix_sizes.row][matrix_sizes.layer]) + { + cell_sizes_[0] = edge_lengths_[0] / matrix_.shape()[0]; + cell_sizes_[1] = edge_lengths_[1] / matrix_.shape()[1]; + cell_sizes_[2] = edge_lengths_[2] / matrix_.shape()[2]; + } + + void diagnosis() const + { + for (matrix_type::size_type i(0); i < matrix_.shape()[0]; ++i) + { + for (matrix_type::size_type j(0); j < matrix_.shape()[1]; ++j) + { + for (matrix_type::size_type k(0); k < matrix_.shape()[2]; ++k) + { + const cell_type& c = matrix_[i][j][k]; + for (cell_type::const_iterator it(c.begin()); it != c.end(); ++it) + { + if (*it >= particles_.size()) + { + throw IllegalState(""out of bounds.""); + } + } + } + } + } + } + + // Space + + virtual Integer num_species() const + { + return particle_pool_.size(); + } + virtual bool has_species(const Species& sp) const + { + return (particle_pool_.find(sp.serial()) != particle_pool_.end()); + } + + virtual std::vector list_species() const + { + std::vector retval; + for (per_species_particle_id_set::const_iterator + i(particle_pool_.begin()); i != particle_pool_.end(); ++i) + { + retval.push_back(Species((*i).first)); + } + return retval; + } + + // ParticleSpaceTraits + + const Real3& edge_lengths() const + { + return edge_lengths_; + } + + const Real3& cell_sizes() const + { + return cell_sizes_; + } + + const Integer3 matrix_sizes() const + { + return Integer3(matrix_.shape()[0], matrix_.shape()[1], matrix_.shape()[2]); + } + + void reset(const Real3& edge_lengths); + + bool update_particle(const ParticleID& pid, const Particle& p); + + const particle_container_type& particles() const + { + return particles_; + } + + std::pair get_particle(const ParticleID& pid) const; + bool has_particle(const ParticleID& pid) const; + void remove_particle(const ParticleID& pid); + + Integer num_particles() const; + Integer num_particles(const Species& sp) const; + Integer num_particles_exact(const Species& sp) const; + Integer num_molecules(const Species& sp) const; + Integer num_molecules_exact(const Species& sp) const; + + std::vector > + list_particles() const; + std::vector > + list_particles(const Species& sp) const; + std::vector > + list_particles_exact(const Species& sp) const; + + virtual void save(const std::string& filename) const + { + throw NotSupported( + ""save(const std::string) is not supported by this space class""); + } + +#ifdef WITH_HDF5 + void save_hdf5(H5::Group* root) const + { + save_particle_space(*this, root); + } + + void load_hdf5(const H5::Group& root) + { + load_particle_space(root, this); + } +#endif + + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius) const; + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore) const; + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const; + +protected: + + // inline cell_index_type index(const Real3& pos, double t = 1e-10) const + inline cell_index_type index(const Real3& pos) const + { + cell_index_type retval = {{ + static_cast( + pos[0] / cell_sizes_[0]) % matrix_.shape()[0], + static_cast( + pos[1] / cell_sizes_[1]) % matrix_.shape()[1], + static_cast( + pos[2] / cell_sizes_[2]) % matrix_.shape()[2] + }}; // std::array + return retval; + } + + inline Real3 offset_index_cyclic( + cell_index_type& i, const cell_offset_type& o) const + { + Real3 retval; + + if (o[0] < 0 && + static_cast(-o[0]) > i[0]) + { + matrix_type::size_type t( + (i[0] + matrix_.shape()[0] - (-o[0] % matrix_.shape()[0])) + % matrix_.shape()[0]); + retval[0] = (o[0] - static_cast(t - i[0])) + * cell_sizes_[0]; + i[0] = t; + } + else if (matrix_.shape()[0] - o[0] <= i[0]) + { + matrix_type::size_type + t((i[0] + (o[0] % matrix_.shape()[0])) % matrix_.shape()[0]); + retval[0] = (o[0] - static_cast(t - i[0])) + * cell_sizes_[0]; + i[0] = t; + } + else + { + i[0] += o[0]; + } + + if (o[1] < 0 && + static_cast(-o[1]) > i[1]) + { + matrix_type::size_type t( + (i[1] + matrix_.shape()[1] - (-o[1] % matrix_.shape()[1])) + % matrix_.shape()[1]); + retval[1] = (o[1] - static_cast(t - i[1])) + * cell_sizes_[1]; + i[1] = t; + } + else if (matrix_.shape()[1] - o[1] <= i[1]) + { + matrix_type::size_type + t((i[1] + (o[1] % matrix_.shape()[1])) % matrix_.shape()[1]); + retval[1] = (o[1] - static_cast(t - i[1])) + * cell_sizes_[1]; + i[1] = t; + } + else + { + i[1] += o[1]; + } + + if (o[2] < 0 && + static_cast(-o[2]) > i[2]) + { + matrix_type::size_type + t((i[2] + matrix_.shape()[2] - (-o[2] % matrix_.shape()[2])) + % matrix_.shape()[2]); + retval[2] = (o[2] - static_cast(t - i[2])) + * cell_sizes_[2]; + i[2] = t; + } + else if (matrix_.shape()[2] - o[2] <= i[2]) + { + matrix_type::size_type t( + (i[2] + (o[2] % matrix_.shape()[2])) % matrix_.shape()[2]); + retval[2] = (o[2] - static_cast(t - i[2])) + * cell_sizes_[2]; + i[2] = t; + } + else + { + i[2] += o[2]; + } + + return retval; + } + + inline const cell_type& cell(const cell_index_type& i) const + { + return matrix_[i[0]][i[1]][i[2]]; + } + + inline cell_type& cell(const cell_index_type& i) + { + return matrix_[i[0]][i[1]][i[2]]; + } + + inline particle_container_type::iterator find(const ParticleID& k) + { + key_to_value_map_type::const_iterator p(rmap_.find(k)); + if (rmap_.end() == p) + { + return particles_.end(); + } + return particles_.begin() + (*p).second; + } + + inline particle_container_type::const_iterator find(const ParticleID& k) const + { + key_to_value_map_type::const_iterator p(rmap_.find(k)); + if (rmap_.end() == p) + { + return particles_.end(); + } + return particles_.begin() + (*p).second; + } + + inline particle_container_type::iterator update( + particle_container_type::iterator const& old_value, + const std::pair& v) + { + cell_type* new_cell(&cell(index(v.second.position()))); + cell_type* old_cell(0); + + if (old_value != particles_.end()) + { + old_cell = &cell(index((*old_value).second.position())); + } + + if (new_cell == old_cell) + { + // reinterpret_cast(*old_value) = v; + *old_value = v; + return old_value; + } + else + { + particle_container_type::size_type idx(0); + + if (old_cell) + { + // reinterpret_cast(*old_value) = v; + *old_value = v; + + cell_type::iterator + i(find_in_cell(old_cell, old_value - particles_.begin())); + idx = *i; + erase_from_cell(old_cell, i); + push_into_cell(new_cell, idx); + } + else + { + idx = particles_.size(); + particles_.push_back(v); + push_into_cell(new_cell, idx); + rmap_[v.first] = idx; + } + return particles_.begin() + idx; + } + } + + inline std::pair update( + const std::pair& v) + { + cell_type* new_cell(&cell(index(v.second.position()))); + particle_container_type::iterator old_value(particles_.end()); + cell_type* old_cell(0); + + { + key_to_value_map_type::const_iterator i(rmap_.find(v.first)); + if (i != rmap_.end()) + { + old_value = particles_.begin() + (*i).second; + old_cell = &cell(index(old_value->second.position())); + } + } + + if (new_cell == old_cell) + { + // reinterpret_cast(*old_value) = v; + *old_value = v; + // return std::pair(old_value, false); + return std::make_pair(old_value, false); + } + else + { + particle_container_type::size_type idx(0); + + if (old_cell) + { + // reinterpret_cast(*old_value) = v; + *old_value = v; + + cell_type::iterator + i(find_in_cell(old_cell, old_value - particles_.begin())); + idx = *i; + erase_from_cell(old_cell, i); + push_into_cell(new_cell, idx); + return std::pair( + particles_.begin() + idx, false); + } + else + { + idx = particles_.size(); + particles_.push_back(v); + push_into_cell(new_cell, idx); + rmap_[v.first] = idx; + return std::pair( + particles_.begin() + idx, true); + } + } + } + + inline bool erase(particle_container_type::iterator const& i) + { + if (particles_.end() == i) + { + return false; + } + + particle_container_type::size_type old_idx(i - particles_.begin()); + cell_type& old_cell(cell(index((*i).second.position()))); + const bool succeeded(erase_from_cell(&old_cell, old_idx)); + if (!succeeded) + { + throw IllegalState(""never get here""); + } + // BOOST_ASSERT(succeeded); + rmap_.erase((*i).first); + + particle_container_type::size_type const last_idx(particles_.size() - 1); + + if (old_idx < last_idx) + { + const std::pair& last(particles_[last_idx]); + cell_type& last_cell(cell(index(last.second.position()))); + const bool tmp(erase_from_cell(&last_cell, last_idx)); + if (!tmp) + { + throw IllegalState(""never get here""); + } + // BOOST_ASSERT(tmp); + push_into_cell(&last_cell, old_idx); + rmap_[last.first] = old_idx; + // reinterpret_cast(*i) = last; + (*i) = last; + } + particles_.pop_back(); + return true; + } + + inline bool erase(const ParticleID& k) + { + key_to_value_map_type::const_iterator p(rmap_.find(k)); + if (rmap_.end() == p) + { + return false; + } + return erase(particles_.begin() + (*p).second); + } + + inline void erase_from_cell(cell_type* c, const cell_type::iterator& i) + { + c->erase(i); + } + + inline cell_type::size_type erase_from_cell( + cell_type* c, const particle_container_type::size_type& v) + { + cell_type::iterator e(c->end()); + std::pair + i(std::equal_range(c->begin(), e, v)); + const cell_type::size_type retval(i.second - i.first); + c->erase(i.first, i.second); + return retval; + } + + inline void push_into_cell( + cell_type* c, const particle_container_type::size_type& v) + { + cell_type::iterator i(std::upper_bound(c->begin(), c->end(), v)); + c->insert(i, v); + } + + inline cell_type::iterator find_in_cell( + cell_type* c, const particle_container_type::size_type& v) + { + cell_type::iterator i(std::lower_bound(c->begin(), c->end(), v)); + if (i != c->end() && *i == v) + { + return i; + } + else + { + return c->end(); + } + } + + inline cell_type::const_iterator find_in_cell( + cell_type* c, const particle_container_type::size_type& v) const + { + cell_type::iterator i(std::lower_bound(c->begin(), c->end(), v)); + if (i != c->end() && *i == v) + { + return i; + } + else + { + return c->end(); + } + } + +protected: + + Real3 edge_lengths_; + + particle_container_type particles_; + key_to_value_map_type rmap_; + per_species_particle_id_set particle_pool_; + + matrix_type matrix_; + Real3 cell_sizes_; +}; + +}; // ecell4 + +#endif /* ECELL4_PARTICLE_SPACE_CELL_LIST_IMPL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/VoxelPool.hpp",".hpp","3339","129","#ifndef ECELL4_MOLECULAR_TYPE_BASE_HPP +#define ECELL4_MOLECULAR_TYPE_BASE_HPP + +#include ""Identifier.hpp"" +#include ""RandomNumberGenerator.hpp"" +#include ""Shape.hpp"" +#include ""Species.hpp"" +#include +#include + +namespace ecell4 +{ + +class VoxelPool +{ +public: + typedef Integer coordinate_type; + + // typedef std::pair coordinate_id_pair_type; + typedef struct coordinate_id_pair_type + { + coordinate_id_pair_type(ParticleID const &pid, + coordinate_type const &coordinate) + : coordinate(coordinate), pid(pid) + { + } + + coordinate_type coordinate; + ParticleID pid; + + bool operator==(const coordinate_id_pair_type &rhs) const + { + return pid == rhs.pid && coordinate == rhs.coordinate; + } + + bool operator!=(const coordinate_id_pair_type &rhs) const + { + return pid != rhs.pid || coordinate != rhs.coordinate; + } + + bool operator<(const coordinate_id_pair_type &rhs) const + { + return coordinate < rhs.coordinate || + (coordinate == rhs.coordinate && pid < rhs.pid); + } + + bool operator>=(const coordinate_id_pair_type &rhs) const + { + return coordinate > rhs.coordinate || + (coordinate == rhs.coordinate && pid >= rhs.pid); + } + + bool operator>(const coordinate_id_pair_type &rhs) const + { + return coordinate > rhs.coordinate || + (coordinate == rhs.coordinate && pid > rhs.pid); + } + + bool operator<=(const coordinate_id_pair_type &rhs) const + { + return coordinate < rhs.coordinate || + (coordinate == rhs.coordinate && pid <= rhs.pid); + } + } coordinate_id_pair_type; + +public: + typedef enum + { + DEFAULT, + VACANT, + STRUCTURE, + INTERFACE + } voxel_type_type; + +public: + VoxelPool(const Species &species, std::weak_ptr location) + : species_(species), location_(location) + { + ; + } + + virtual ~VoxelPool() { ; } + + virtual voxel_type_type const voxel_type() const = 0; + +public: + bool is_vacant() const + { + return voxel_type() == VACANT || location_.expired(); + } + + bool is_structure() const { return voxel_type() == STRUCTURE; } + + bool is_interface() const { return voxel_type() == INTERFACE; } + + const Species &species() const { return species_; } + + std::shared_ptr location() const { return location_.lock(); } + +public: + virtual const Integer size() const = 0; + + virtual void add_voxel(const coordinate_id_pair_type &info) = 0; + + virtual void replace_voxel(const coordinate_type &from_coord, + const coordinate_type &to_coord, + const std::size_t candidate = 0) + { + ; // do nothing + } + + virtual coordinate_id_pair_type pop(const coordinate_type &coord) = 0; + + virtual bool remove_voxel_if_exists(const coordinate_type &coord) = 0; + + virtual const ParticleID get_particle_id(const coordinate_type &coord) const + { + return ParticleID(); + } + +protected: + const Species species_; + std::weak_ptr location_; +}; + +} // namespace ecell4 + +#endif +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Real3.hpp",".hpp","5054","252","#ifndef ECELL4_REAL3_HPP +#define ECELL4_REAL3_HPP + +#include +#include +#include +#include +#include +#include + +#include + +#include ""types.hpp"" +#include ""functions.hpp"" + +namespace ecell4 +{ + +struct Real3 + : public boost::array +{ + typedef boost::array base_type; + typedef base_type::value_type value_type; + typedef base_type::size_type size_type; + + Real3& operator+=(const Real3& rhs); + Real3& operator-=(const Real3& rhs); + Real3& operator*=(const Real3::value_type& rhs); + Real3& operator/=(const Real3::value_type& rhs); + + Real3() + { + (*this)[0] = 0; + (*this)[1] = 0; + (*this)[2] = 0; + } + + Real3(value_type p0, value_type p1, value_type p2) + { + (*this)[0] = p0; + (*this)[1] = p1; + (*this)[2] = p2; + } + + Real3(const Real3 &rhs) + { + (*this)[0] = rhs[0]; + (*this)[1] = rhs[1]; + (*this)[2] = rhs[2]; + } + + // Real3(const Real (&a)[3]) + // : base_type(*reinterpret_cast(&a)) + // { + // ; + // } + + // Real3(const Real a[3]) + // : base_type(*reinterpret_cast(a)) + // { + // ; + // } + + // Real3(const base_type& a) + // : base_type(a) + // { + // ; + // } +}; + +inline Real3 add(const Real3& p1, const Real3& p2) +{ + Real3 retval; + retval[0] = p1[0] + p2[0]; + retval[1] = p1[1] + p2[1]; + retval[2] = p1[2] + p2[2]; + return retval; +} + +inline Real3 subtract(const Real3& p1, const Real3& p2) +{ + Real3 retval; + retval[0] = p1[0] - p2[0]; + retval[1] = p1[1] - p2[1]; + retval[2] = p1[2] - p2[2]; + return retval; +} + +inline Real3 divide(const Real3& p1, const Real3::value_type& p2) +{ + Real3 retval; + retval[0] = p1[0] / p2; + retval[1] = p1[1] / p2; + retval[2] = p1[2] / p2; + return retval; +} + +inline Real3 multiply(const Real3& p1, const Real3::value_type& p2) +{ + Real3 retval; + retval[0] = p1[0] * p2; + retval[1] = p1[1] * p2; + retval[2] = p1[2] * p2; + return retval; +} + +inline Real3 modulo(const Real3& p1, const Real3::value_type& p2) +{ + Real3 retval; + retval[0] = modulo(p1[0], p2); + retval[1] = modulo(p1[1], p2); + retval[2] = modulo(p1[2], p2); + return retval; +} + +inline Real3 modulo(const Real3& p1, const Real3& p2) +{ + Real3 retval; + retval[0] = modulo(p1[0], p2[0]); + retval[1] = modulo(p1[1], p2[1]); + retval[2] = modulo(p1[2], p2[2]); + return retval; +} + +inline Real3 abs(const Real3& v) +{ + Real3 retval; + retval[0] = abs(v[0]); + retval[1] = abs(v[1]); + retval[2] = abs(v[2]); + return retval; +} + +inline Real3::value_type dot_product( + const Real3& p1, const Real3& p2) +{ + return p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]; +} + +inline Real3 cross_product(const Real3& p1, const Real3& p2) +{ + Real3 retval; + retval[0] = p1[1] * p2[2] - p1[2] * p2[1]; + retval[1] = p1[2] * p2[0] - p1[0] * p2[2]; + retval[2] = p1[0] * p2[1] - p1[1] * p2[0]; + return retval; +} + +inline Real3::value_type length_sq(const Real3& r) +{ + return pow_2(r[0]) + pow_2(r[1]) + pow_2(r[2]); +} + +inline Real3::value_type length(const Real3& r) +{ + return std::sqrt(length_sq(r)); +} + +inline Real3 operator+(const Real3& lhs, const Real3& rhs) +{ + return add(lhs, rhs); +} + +inline Real3 operator-(const Real3& lhs, const Real3& rhs) +{ + return subtract(lhs, rhs); +} + +inline Real3 operator/( + const Real3& lhs, const Real3::value_type& rhs) +{ + return divide(lhs, rhs); +} + +inline Real3 operator*( + const Real3& lhs, const Real3::value_type& rhs) +{ + return multiply(lhs, rhs); +} + +inline Real3& Real3::operator+=(const Real3& rhs) +{ + *this = add(*this, rhs); + return *this; +} + +inline Real3& Real3::operator-=(const Real3& rhs) +{ + *this = subtract(*this, rhs); + return *this; +} + +inline Real3& Real3::operator*=(const Real3::value_type& rhs) +{ + *this = multiply(*this, rhs); + return *this; +} + +inline Real3& Real3::operator/=(const Real3::value_type& rhs) +{ + *this = divide(*this, rhs); + return *this; +} + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& strm, const Real3& v) +{ + strm << std::setprecision(12) + << ""("" << v[0] << "", "" << v[1] << "", "" << v[2] << "")""; + return strm; +} + +inline Real3 ones() +{ + return Real3(1.0, 1.0, 1.0); +} + +inline Real3 unitx() +{ + return Real3(1.0, 0.0, 0.0); +} + +inline Real3 unity() +{ + return Real3(0.0, 1.0, 0.0); +} + +inline Real3 unitz() +{ + return Real3(0.0, 0.0, 1.0); +} + +} // ecell4 + +namespace std { +template<> +struct hash +{ + typedef ecell4::Real3 argument_type; + + std::size_t operator()(argument_type const& val) + { + return hash()(val[0]) ^ + hash()(val[1]) ^ + hash()(val[2]); + } +}; +} // std + +#endif /* ECELL4_REAL3_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/STLFileIO.hpp",".hpp","799","30","#ifndef ECELL4_STL_FILE_READER +#define ECELL4_STL_FILE_READER +#include +#include +#include +#include + +namespace ecell4 +{ + +class Polygon; // forward declaration + +enum class STLFormat : std::uint8_t +{ + Ascii = 0, + Binary = 1, +}; + +std::vector read_stl_format(const std::string& fname, const STLFormat); +void write_stl_format(const std::string& fname, const STLFormat, + const std::vector& triangles); + +Polygon read_polygon(const std::string& filename, const STLFormat, + const Real3& edge_lengths); +void write_polygon(const std::string& filename, const STLFormat, + const Polygon&); + +}// ecell4 +#endif /* ECELL4_STL_FILE_READER */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/OffLatticeSpace.cpp",".cpp","7242","256","#include ""Context.hpp"" +#include ""MoleculePool.hpp"" +#include ""OffLatticeSpace.hpp"" +#include ""VacantType.hpp"" +#include + +namespace ecell4 +{ + +OffLatticeSpace::OffLatticeSpace(const Real &voxel_radius, + const Species &species) + : base_type(voxel_radius), voxels_(), positions_(), adjoinings_() +{ + vacant_ = std::shared_ptr( + new StructureType(species, std::weak_ptr())); +} + +OffLatticeSpace::OffLatticeSpace( + const Real &voxel_radius, const Species &species, + const position_container &positions, + const coordinate_pair_list_type &adjoining_pairs) + : base_type(voxel_radius), voxels_(), positions_(), adjoinings_() +{ + vacant_ = std::shared_ptr( + new StructureType(species, std::weak_ptr())); + reset(positions, adjoining_pairs); +} + +OffLatticeSpace::~OffLatticeSpace() {} + +void OffLatticeSpace::reset(const position_container &positions, + const coordinate_pair_list_type &adjoining_pairs) +{ + voxels_.clear(); + positions_.clear(); + adjoinings_.clear(); + + const std::size_t size(positions.size()); + + voxels_.resize(size, vacant_); + positions_.resize(size); + adjoinings_.resize(size); + + for (coordinate_type coord(0); coord < static_cast(size); ++coord) + { + vacant_->add_voxel(coordinate_id_pair_type(ParticleID(), coord)); + } + + std::copy(positions.begin(), positions.end(), positions_.begin()); + + for (coordinate_pair_list_type::const_iterator itr(adjoining_pairs.begin()); + itr != adjoining_pairs.end(); ++itr) + { + const coordinate_type coord0((*itr).first); + const coordinate_type coord1((*itr).second); + + if (is_in_range(coord0) && is_in_range(coord1)) + { + adjoinings_.at(coord0).push_back(coord1); + adjoinings_.at(coord1).push_back(coord0); + } + else + { + throw IllegalState(""A given pair is invalid.""); + } + } +} + +boost::optional +OffLatticeSpace::get_coord(const ParticleID &pid) const +{ + if (pid == ParticleID()) + return boost::none; + + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + { + const std::shared_ptr &vp((*itr).second); + for (MoleculePool::const_iterator vitr(vp->begin()); vitr != vp->end(); + ++vitr) + { + if ((*vitr).pid == pid) + { + return (*vitr).coordinate; + } + } + } + // throw NotFound(""A corresponding particle is not found""); + return boost::none; +} + +/* + * public functions + */ + +// Same as LatticeSpaceVectorImpl +bool OffLatticeSpace::update_voxel(const ParticleID &pid, + const Species &species, + const coordinate_type to_coord) +{ + if (!is_in_range(to_coord)) + throw NotSupported(""Out of bounds""); + + std::shared_ptr new_vp(find_voxel_pool(species)); + std::shared_ptr dest_vp(get_voxel_pool_at(to_coord)); + + if (dest_vp != new_vp->location()) + { + throw NotSupported(""Mismatch in the location. Failed to place '"" + + new_vp->species().serial() + ""' to '"" + + dest_vp->species().serial() + ""'.""); + } + + if (boost::optional from_coord = get_coord(pid)) + { + // move + voxels_.at(*from_coord)->remove_voxel_if_exists(*from_coord); + + // XXX: use location? + dest_vp->replace_voxel(to_coord, *from_coord); + voxels_.at(*from_coord) = dest_vp; + + new_vp->add_voxel(coordinate_id_pair_type(pid, to_coord)); + voxels_.at(to_coord) = new_vp; + + return false; + } + + // new + dest_vp->remove_voxel_if_exists(to_coord); + + new_vp->add_voxel(coordinate_id_pair_type(pid, to_coord)); + voxels_.at(to_coord) = new_vp; + + return true; +} + +bool OffLatticeSpace::add_voxel(const Species &species, const ParticleID &pid, + const coordinate_type &coord) +{ + std::shared_ptr vpool(find_voxel_pool(species)); + std::shared_ptr location(get_voxel_pool_at(coord)); + + if (vpool->location() != location) + return false; + + location->remove_voxel_if_exists(coord); + vpool->add_voxel(coordinate_id_pair_type(pid, coord)); + voxels_.at(coord) = vpool; + + return true; +} + +// Same as LatticeSpaceVectorImpl +bool OffLatticeSpace::remove_voxel(const ParticleID &pid) +{ + for (molecule_pool_map_type::iterator i(molecule_pools_.begin()); + i != molecule_pools_.end(); ++i) + { + const std::shared_ptr &vp((*i).second); + MoleculePool::const_iterator j(vp->find(pid)); + if (j != vp->end()) + { + const coordinate_type coord((*j).coordinate); + if (!vp->remove_voxel_if_exists(coord)) + { + return false; + } + + voxels_.at(coord) = vp->location(); + + vp->location()->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + return true; + } + } + return false; +} + +// Same as LatticeSpaceVectorImpl +bool OffLatticeSpace::remove_voxel(const coordinate_type &coord) +{ + std::shared_ptr vp(voxels_.at(coord)); + if (auto location_ptr = vp->location()) + { + if (vp->remove_voxel_if_exists(coord)) + { + voxels_.at(coord) = location_ptr; + location_ptr->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + return true; + } + } + return false; +} + +bool OffLatticeSpace::can_move(const coordinate_type &src, + const coordinate_type &dest) const +{ + if (src == dest) + return false; + + std::shared_ptr src_vp(voxels_.at(src)); + if (src_vp->is_vacant()) + return false; + + std::shared_ptr dest_vp(voxels_.at(dest)); + + return (voxels_.at(dest) == src_vp->location()); +} + +bool OffLatticeSpace::move(const coordinate_type &src, + const coordinate_type &dest, + const std::size_t candidate) +{ + if (src == dest) + return false; + + std::shared_ptr src_vp(voxels_.at(src)); + if (src_vp->is_vacant()) + return true; + + std::shared_ptr dest_vp(voxels_.at(dest)); + if (dest_vp != src_vp->location()) + return false; + + src_vp->replace_voxel(src, dest, candidate); + voxels_.at(src) = dest_vp; + + dest_vp->replace_voxel(dest, src); + voxels_.at(dest) = src_vp; + + return true; +} + +OffLatticeSpace::coordinate_type +OffLatticeSpace::position2coordinate(const Real3 &pos) const +{ + coordinate_type coordinate(0); + Real shortest_length = length(positions_.at(0) - pos); + + for (coordinate_type coord(1); coord < size(); ++coord) + { + const Real len(length(positions_.at(coord) - pos)); + if (len < shortest_length) + { + coordinate = coord; + shortest_length = len; + } + } + + return coordinate; +} + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/OffLatticeSpace.hpp",".hpp","3612","136","#ifndef ECELL4_OFFLATTICE_SPACE_HPP +#define ECELL4_OFFLATTICE_SPACE_HPP + +#include ""VoxelSpaceBase.hpp"" +#include + +namespace ecell4 +{ + +class OffLatticeSpace : public VoxelSpaceBase +{ +protected: + typedef VoxelSpaceBase base_type; + typedef std::vector> voxel_container; + typedef std::vector> adjoining_container; + +public: + typedef std::pair coordinate_pair_type; + typedef std::vector position_container; + typedef std::vector coordinate_pair_list_type; + + /* + * Constructor and Destructor + */ + OffLatticeSpace(const Real &voxel_radius, const Species &species); + OffLatticeSpace(const Real &voxel_radius, const Species &species, + const position_container &positions, + const coordinate_pair_list_type &adjoining_pairs); + ~OffLatticeSpace(); + + /* + * Space Traits + */ +#ifdef WITH_HDF5 + void save_hdf5(H5::Group *root) const + { + throw NotSupported(""OffLatticeSpace::save_hdf5 is not supported.""); + } + + void load_hdf5(const H5::Group &root) + { + throw NotSupported(""OffLatticeSpace::load_hdf5 is not supported.""); + } +#endif + + /* + * ParticleSpace Traits + */ + const Real3 &edge_lengths() const { return edge_lengths_; } + + // tmp + void set_lengths(const Real3 &edge_lengths) + { + edge_lengths_ = edge_lengths; + } + + /* + * VoxelSpace Traits + */ + std::shared_ptr + get_voxel_pool_at(const coordinate_type &coord) const + { + return voxels_.at(coord); + } + + /* + * Coordinate Transformation + */ + Real3 coordinate2position(const coordinate_type &coord) const + { + return positions_.at(coord); + } + + coordinate_type position2coordinate(const Real3 &pos) const; + + /* + * Neighbor + */ + Integer num_neighbors(const coordinate_type &coord) const + { + return adjoinings_.at(coord).size(); + } + + coordinate_type get_neighbor(const coordinate_type &coord, + const Integer &nrand) const + { + return adjoinings_.at(coord).at(nrand); + } + + /* + * Voxel Manipulation + */ + bool update_voxel(const ParticleID &pid, const Species &species, + const coordinate_type coordinate); + bool add_voxel(const Species &species, const ParticleID &pid, + const coordinate_type &coord); + bool remove_voxel(const ParticleID &pid); + bool remove_voxel(const coordinate_type &coord); + + bool can_move(const coordinate_type &src, + const coordinate_type &dest) const; + + bool move(const coordinate_type &src, const coordinate_type &dest, + const std::size_t candidate = 0); + + Integer size() const { return voxels_.size(); } + + Integer3 shape() const + { + throw NotSupported(""OffLatticeSpace::shape() is not supported.""); + } + + Integer actual_size() const { return size(); } + +protected: + bool is_in_range(const coordinate_type &coord) const + { + return 0 <= coord && coord < static_cast(voxels_.size()); + } + + void reset(const position_container &positions, + const coordinate_pair_list_type &adjoining_pairs); + boost::optional get_coord(const ParticleID &pid) const; + +protected: + voxel_container voxels_; + position_container positions_; + adjoining_container adjoinings_; + + Real3 edge_lengths_; +}; + +} // namespace ecell4 + +#endif /* ECELL4_OFFLATTICE_SPACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpace.hpp",".hpp","12237","445","#ifndef ECELL4_PARTICLE_SPACE_HPP +#define ECELL4_PARTICLE_SPACE_HPP + +#include +#include + +#include ""types.hpp"" +#include ""functions.hpp"" +#include ""exceptions.hpp"" +#include ""Real3.hpp"" +#include ""Particle.hpp"" +#include ""Species.hpp"" +// #include ""Space.hpp"" + +#ifdef WITH_HDF5 +#include ""ParticleSpaceHDF5Writer.hpp"" +#endif + +namespace ecell4 +{ + +class ParticleSpace + // : public Space +{ +public: + + typedef std::vector > + particle_container_type; + +public: + + ParticleSpace() + : t_(0.0) + { + ; + } + + virtual ~ParticleSpace() + { + ; // do nothing + } + + // SpaceTraits + + const Real t() const + { + return t_; + } + + void set_t(const Real& t) + { + if (t < 0.0) + { + throw std::invalid_argument(""the time must be positive.""); + } + t_ = t; + } + + // ParticleSpaceTraits + + /** + * get the axes lengths of a cuboidal region. + * this function is a part of the trait of ParticleSpace. + * @return edge lengths Real3 + */ + virtual const Real3& edge_lengths() const + { + throw NotImplemented(""edge_lengths() not implemented""); + } + + virtual Integer num_molecules(const Species& sp) const + { + return num_molecules_exact(sp); + } + + virtual Integer num_molecules_exact(const Species& sp) const + { + throw NotImplemented(""num_molecules_exact(const Species&) not implemented""); + } + + /** + * get the number of particles. + * this function is a part of the trait of ParticleSpace. + * @return a number of particles Integer + */ + virtual Integer num_particles() const + { + throw NotImplemented(""num_particles() not implemented""); + } + + /** + * get the number of particles. + * this function is a part of the trait of ParticleSpace. + * @param sp a species + * @return a number of particles Integer + */ + virtual Integer num_particles(const Species& sp) const + { + return num_particles_exact(sp); + } + + virtual Integer num_particles_exact(const Species& sp) const + { + throw NotImplemented(""num_particles_exact(const Species&) not implemented""); + } + + /** + * get all particles. + * this function is a part of the trait of ParticleSpace. + * @return a list of particles + */ + virtual std::vector > + list_particles() const + { + throw NotImplemented(""list_particles() not implemented""); + } + + /** + * get particles. + * this function is a part of the trait of ParticleSpace. + * @param sp a species + * @return a list of particles + */ + virtual std::vector > + list_particles(const Species& sp) const + { + return list_particles_exact(sp); + } + + virtual std::vector > + list_particles_exact(const Species& sp) const + { + throw NotImplemented(""list_particles_exact(const Species&) not implemented""); + } + + /** + * check if the particle exists. + * this function is a part of the trait of ParticleSpace. + * @param pid an ID for the particle + * @return if the particle exists or not bool + */ + virtual bool has_particle(const ParticleID& pid) const + { + throw NotImplemented(""has_particle(const ParticleID&) not implemented.""); + } + + virtual std::vector list_species() const + { + const particle_container_type& pcont(particles()); + std::vector retval; + for (particle_container_type::const_iterator i(pcont.begin()); + i != pcont.end(); ++i) + { + const Species& sp((*i).second.species()); + if (std::find(retval.begin(), retval.end(), sp) + == retval.end()) + { + retval.push_back(sp); + } + } + return retval; + } + +#ifdef WITH_HDF5 + virtual void save_hdf5(H5::Group* root) const = 0; + virtual void load_hdf5(const H5::Group& root) = 0; +#endif + + // ParticleSpace member functions + + /** + * update a particle specified by its ID. + * if the particle does not exist, create a new particle. + * this function is a member of ParticleSpace + * @param pid ParticleID + * @param p Particle + * @return if the particle does not exist or not bool + */ + virtual bool update_particle(const ParticleID& pid, const Particle& p) = 0; + + /** + * get a particle specified with an ID. + * this function is a member of ParticleSpace + * @param pid ParticleID + * @return a pair of ParticleID and Particle + */ + virtual std::pair + get_particle(const ParticleID& pid) const = 0; + + /** + * remove a particle + * this function is a member of ParticleSpace + * @param pid ParticleID + */ + virtual void remove_particle(const ParticleID& pid) = 0; + + /** + * get particles within a spherical region. + * this function is a part of the trait of ParticleSpace. + * @param pos a center position of the sphere + * @param radius a radius of the sphere + * @return a list of particles + */ + virtual std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius) const = 0; + + /** + * get particles within a spherical region except for ignore(s). + * this function is a part of the trait of ParticleSpace. + * @param pos a center position of the sphere + * @param radius a radius of the sphere + * @param ignore an ignored ID + * @return a list of particles + */ + virtual std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore) const = 0; + + /** + * get particles within a spherical region except for ignore(s). + * this function is a part of the trait of ParticleSpace. + * @param pos a center position of the sphere + * @param radius a radius of the sphere + * @param ignore1 an ignored ID + * @param ignore2 an ignored ID + * @return a list of particles + */ + virtual std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const = 0; + + /** + * transpose a position based on the periodic boundary condition. + * this function is a part of the trait of ParticleSpace. + * @param pos1 a target position + * @param pos2 a reference position + * @return a transposed position Real3 + */ + Real3 periodic_transpose( + const Real3& pos1, const Real3& pos2) const + { + Real3 retval(pos1); + const Real3& edges(edge_lengths()); + for (Real3::size_type dim(0); dim < 3; ++dim) + { + const Real edge_length(edges[dim]); + const Real diff(pos2[dim] - pos1[dim]), half(edge_length * 0.5); + + if (diff > half) + { + retval[dim] += edge_length; + } + else if (diff < -half) + { + retval[dim] -= edge_length; + } + } + return retval; + } + + /** + * transpose a position based on the periodic boundary condition. + * if the position is in the region, returns the original position. + * this function is a part of the trait of ParticleSpace. + * @param pos a target position + * @return a transposed position Real3 + */ + inline Real3 apply_boundary(const Real3& pos) const + { + return modulo(pos, edge_lengths()); + } + + /** + * calculate a square of the distance between positions + * this function is a part of the trait of ParticleSpace. + * @param pos1 + * @param pos2 + * @return a square of the distance + */ + Real distance_sq( + const Real3& pos1, const Real3& pos2) const + { + // Real retval(0); + // const Real3& edges(edge_lengths()); + // for (Real3::size_type dim(0); dim < 3; ++dim) + // { + // const Real edge_length(edges[dim]); + // const Real diff(pos2[dim] - pos1[dim]), half(edge_length * 0.5); + + // if (diff > half) + // { + // retval += pow_2(diff - edge_length); + // } + // else if (diff < -half) + // { + // retval += pow_2(diff + edge_length); + // } + // else + // { + // retval += pow_2(diff); + // } + // } + // return retval; + + return length_sq(subtract(pos1, periodic_transpose(pos2, pos1))); + } + + /** + * calculate the distance between positions + * this function is a part of the trait of ParticleSpace. + * @param pos1 + * @param pos2 + * @return the distance + */ + inline Real distance(const Real3& pos1, const Real3& pos2) const + { + return std::sqrt(distance_sq(pos1, pos2)); + } + + // Optional members + + virtual const particle_container_type& particles() const = 0; + + virtual Real get_value(const Species& sp) const + { + return static_cast(num_molecules(sp)); + } + + virtual Real get_value_exact(const Species& sp) const + { + return static_cast(num_molecules_exact(sp)); + } + + virtual const Real volume() const + { + const Real3& size(edge_lengths()); + return size[0] * size[1] * size[2]; + } + +protected: + + Real t_; +}; + +class ParticleSpaceVectorImpl + : public ParticleSpace +{ +public: + + typedef ParticleSpace base_type; + typedef ParticleSpace::particle_container_type particle_container_type; + +protected: + + typedef std::unordered_map< + ParticleID, particle_container_type::size_type> particle_map_type; + +public: + + ParticleSpaceVectorImpl(const Real3& edge_lengths) + { + reset(edge_lengths); + } + + // ParticleSpaceTraits + + const Real3& edge_lengths() const + { + return edge_lengths_; + } + + Integer num_particles() const; + Integer num_particles(const Species& sp) const; + Integer num_particles_exact(const Species& sp) const; + std::vector > list_particles() const; + std::vector > + list_particles(const Species& sp) const; + std::vector > + list_particles_exact(const Species& sp) const; + bool has_particle(const ParticleID& pid) const; + + // ParticleSpace member functions + + bool update_particle(const ParticleID& pid, const Particle& p); + std::pair get_particle(const ParticleID& pid) const; + void remove_particle(const ParticleID& pid); + + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius) const; + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore) const; + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const; + + // CompartmentSpaceTraits + + Integer num_molecules(const Species& sp) const; + Integer num_molecules_exact(const Species& sp) const; + + // Optional members + + const particle_container_type& particles() const + { + return particles_; + } + + virtual void save(const std::string& filename) const + { + throw NotSupported( + ""save(const std::string) is not supported by this space class""); + } + +#ifdef WITH_HDF5 + void save_hdf5(H5::Group* root) const + { + save_particle_space(*this, root); + } + + void load_hdf5(const H5::Group& root) + { + load_particle_space(root, this); + } +#endif + + void reset(const Real3& edge_lengths); + +protected: + + Real3 edge_lengths_; + particle_container_type particles_; + particle_map_type index_map_; +}; + +} // ecell4 + +#endif /* ECELL4_PARTICLE_SPACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Cylinder.hpp",".hpp","2461","120","#ifndef ECELL4_CYLINDER_HPP +#define ECELL4_CYLINDER_HPP + +#include +#include ""Shape.hpp"" + +namespace ecell4 +{ + +struct CylindricalSurface; + +struct Cylinder + : public Shape +{ +public: + + /** for epdp + */ + typedef Real3 position_type; + typedef position_type::value_type length_type; + typedef position_type::value_type value_type; + +public: + + Cylinder(); + Cylinder(const Real3& center, const Real radius, + const Real3& axis, const Real half_height); + Cylinder(const Cylinder& rhs); + + const Real& radius() const; + const Real3& center() const; + const Real& half_height() const; + const Real3& axis() const; + + Real is_inside(const Real3& coord) const; + Real distance(const Real3& pos) const; + bool test_AABB(const Real3& l, const Real3& u) const; + CylindricalSurface surface() const; + Real3 draw_position( + std::shared_ptr& rng) const; + + inline const Real3& position() const + { + return center(); + } + + Real3& position() + { + return center_; + } + + inline const Real& size() const + { + return radius_; + } + + Real& size() + { + return radius_; + } + + inline std::pair to_internal(const Real3& pos) const + { + const Real3 v(pos - center_); + const Real z(dot_product(v, axis_)); + const Real r(length(v - multiply(axis_, z))); + return std::make_pair(r, z); + } + + dimension_kind dimension() const + { + return THREE; + } + +protected: + + Real3 center_; + Real radius_; + Real3 axis_; + Real half_height_; +}; + +struct CylindricalSurface + : public Shape +{ + CylindricalSurface(); + CylindricalSurface(const Real3& center, const Real radius, + const Real3& axis, const Real half_height); + CylindricalSurface(const CylindricalSurface& rhs); + + const Real& radius() const; + const Real3& center() const; + const Real& half_height() const; + const Real3& axis() const; + + Real is_inside(const Real3& coord) const; + Real distance(const Real3& pos) const; + Cylinder inside() const; + Real3 draw_position( + std::shared_ptr& rng) const; + bool test_AABB(const Real3& l, const Real3& u) const; + + dimension_kind dimension() const + { + return TWO; + } + +protected: + + Real3 center_; + Real radius_; + Real3 axis_; + Real half_height_; +}; + +} // ecell4 + +#endif /* ECELL4_CYLINDER_HPP */ + +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/LatticeSpaceHDF5Writer.hpp",".hpp","12722","336","#ifndef ECELL4_LATTICE_SPACE_HDF5_WRITER_HPP +#define ECELL4_LATTICE_SPACE_HDF5_WRITER_HPP + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include ""MoleculePool.hpp"" +#include ""Species.hpp"" +#include ""StructureType.hpp"" +#include ""VacantType.hpp"" +#include ""VoxelPool.hpp"" +#include ""VoxelSpaceBase.hpp"" +#include ""VoxelView.hpp"" +#include ""types.hpp"" + +#include ""Space.hpp"" // just for Space::space_kind + +namespace ecell4 +{ + +struct LatticeSpaceHDF5Traits +{ + struct h5_species_struct + { + char location[32]; + uint32_t is_structure; + }; + + struct h5_voxel_struct + { + uint32_t lot; + uint32_t serial; + uint64_t coordinate; + }; + + static H5::CompType get_voxel_comp() + { + H5::CompType voxel_comp_type(sizeof(h5_voxel_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(voxel_comp_type.getId(), #member, \ + HOFFSET(h5_voxel_struct, member), type.getId()) + INSERT_MEMBER(lot, H5::PredType::NATIVE_INT); + INSERT_MEMBER(serial, H5::PredType::NATIVE_INT); + INSERT_MEMBER(coordinate, H5::PredType::STD_I64LE); +#undef INSERT_MEMBER + return voxel_comp_type; + } + + static void save_voxel_pool(const VoxelPool *mtb, + std::vector voxels, H5::Group *group) + { + const Species species(mtb->species()); + std::unique_ptr mtgroup( + new H5::Group(group->createGroup(species.serial().c_str()))); + + h5_species_struct property; + std::shared_ptr loc(mtb->location()); + // if (loc->is_vacant()) + // property.location = H5std_string(""""); + // else + // property.location = + // H5std_string(loc->species().serial().c_str()); + if (loc->is_vacant()) + std::strcpy(property.location, """"); + else + std::strcpy(property.location, loc->species().serial().c_str()); + property.is_structure = mtb->is_structure() ? 1 : 0; + + mtgroup + ->createAttribute(""location"", H5::StrType(H5::PredType::C_S1, 32), + H5::DataSpace(H5S_SCALAR)) + .write(H5::StrType(H5::PredType::C_S1, 32), &property.location); + // mtgroup->createAttribute(""location"", H5::StrType(0, H5T_VARIABLE), + // H5::DataSpace(H5S_SCALAR) + // ).write(H5::StrType(0, H5T_VARIABLE), &property.location); + mtgroup + ->createAttribute(""is_structure"", H5::PredType::STD_I32LE, + H5::DataSpace(H5S_SCALAR)) + .write(H5::PredType::STD_I32LE, &property.is_structure); + + // Save voxels + const Integer num_voxels(voxels.size()); + std::size_t vidx(0); + std::unique_ptr h5_voxel_array( + new h5_voxel_struct[num_voxels]); + for (const auto &view : voxels) + { + h5_voxel_array[vidx].lot = view.pid.lot(); + h5_voxel_array[vidx].serial = view.pid.serial(); + h5_voxel_array[vidx].coordinate = view.voxel; + ++vidx; + } + + H5::CompType voxel_comp_type(get_voxel_comp()); + hsize_t dims[] = {(hsize_t)num_voxels}; + H5::DataSpace dspace(/* RANK= */ 1, dims); + std::unique_ptr dset(new H5::DataSet( + mtgroup->createDataSet(""voxels"", voxel_comp_type, dspace))); + dset->write(h5_voxel_array.get(), dset->getDataType()); + } + + template + static void save_voxel_pool_recursively( + const Species &location, + std::multimap &location_map, Tspace_ &space, + H5::Group *root) + { + std::multimap::iterator itr; + while ((itr = location_map.find(location)) != location_map.end()) + { + const VoxelPool *mtb((*itr).second); + const Species species(mtb->species()); + save_voxel_pool(mtb, space.list_voxels_exact(species), root); + save_voxel_pool_recursively(species, location_map, space, root); + location_map.erase(itr); + } + } + + static void + sort_by_location(std::multimap location_map, + std::vector &species, + const std::string location = """") + { + std::multimap::iterator itr; + while ((itr = location_map.find(location)) != location_map.end()) + { + const Species sp((*itr).second); + species.push_back(sp); + sort_by_location(location_map, species, sp.serial()); + location_map.erase(itr); + } + } +}; + +template +void save_lattice_space(const Tspace_ &space, H5::Group *root, + const std::string &impl = """") +{ + typedef LatticeSpaceHDF5Traits traits_type; + + std::unique_ptr spgroup( + new H5::Group(root->createGroup(""species""))); + + const std::vector species(space.list_species()); + std::multimap location_map; + for (const auto &sp : species) + { + std::shared_ptr mtb(space.find_voxel_pool(sp)); + Species location(mtb->location()->species()); + location_map.insert( + std::make_pair(location, mtb.get())); // XXX: remove .get() + } + traits_type::save_voxel_pool_recursively( + space.vacant()->species(), location_map, space, spgroup.get()); + + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + const Real3 lengths(space.edge_lengths()); + + const uint32_t space_type(static_cast(Space::LATTICE)); + const double t(space.t()); + const double voxel_radius(space.voxel_radius()); + const uint32_t is_periodic(space.is_periodic() ? 1 : 0); + double edge_lengths[] = {lengths[0], lengths[1], lengths[2]}; + + char implementation[32]; + std::strcpy(implementation, impl.c_str()); + +#define CREATE_ATTRIBUTE(attribute, type) \ + root->createAttribute(#attribute, type, H5::DataSpace(H5S_SCALAR)) \ + .write(type, &attribute) + CREATE_ATTRIBUTE(space_type, H5::PredType::STD_I32LE); + CREATE_ATTRIBUTE(t, H5::PredType::IEEE_F64LE); + CREATE_ATTRIBUTE(voxel_radius, H5::PredType::IEEE_F64LE); + CREATE_ATTRIBUTE(is_periodic, H5::PredType::STD_I32LE); + CREATE_ATTRIBUTE(edge_lengths, lengths_type); + // CREATE_ATTRIBUTE(impl, H5::StrType(0, H5T_VARIABLE)); + CREATE_ATTRIBUTE(implementation, H5::StrType(H5::PredType::C_S1, 32)); +#undef CREATE_ATTRIBUTE +} + +template +void load_lattice_space(const H5::Group &root, Tspace_ *space, + const std::string &implementation = """") +{ + typedef LatticeSpaceHDF5Traits traits_type; + + uint32_t space_type; // not use + double t; + double voxel_radius; + Real3 edge_lengths; + const hsize_t dims[] = {3}; + uint32_t is_periodic; + char impl_C[32]; + // std::string impl = """"; + +#define OPEN_ATTRIBUTE(attribute, type) \ + root.openAttribute(#attribute).read(type, &attribute) + OPEN_ATTRIBUTE(space_type, H5::PredType::STD_I32LE); + OPEN_ATTRIBUTE(t, H5::PredType::IEEE_F64LE); + OPEN_ATTRIBUTE(voxel_radius, H5::PredType::IEEE_F64LE); + OPEN_ATTRIBUTE(edge_lengths, + H5::ArrayType(H5::PredType::NATIVE_DOUBLE, 1, dims)); + OPEN_ATTRIBUTE(is_periodic, H5::PredType::STD_I32LE); +#undef OPEN_ATTRIBUTE + + // if (root.attrExists(""implementation"")) + // root.openAttribute(""implementation"").read( + // H5::StrType(0, H5T_VARIABLE), impl); //XXX: '&' is not needed + // for HDF5std_string + // if (root.attrExists(""implementation"")) + // root.openAttribute(""implementation"").read( + // H5::StrType(H5::PredType::C_S1, 32), impl_C); + + try + { + root.openAttribute(""implementation"") + .read(H5::StrType(H5::PredType::C_S1, 32), impl_C); + } + catch (const H5::AttributeIException &e) + { + // XXX: H5::Location::attrExists is not available in the old version + ; // no attribute exists. do nothing + } + + const std::string impl(impl_C); + + if (implementation != """" && implementation != impl) + { + throw_exception(""Implementation mismatch between "" + ""LatticeSpaces given and saved in the HDF5 ['"", implementation, + ""' != '"", impl, ""'].""); + } + + space->set_t(t); + space->reset(edge_lengths, voxel_radius, (is_periodic != 0)); + + std::map struct_map; + std::map>> voxels_map; + std::multimap location_map; + + std::map>>> + tmp_map; + + H5::Group spgroup(root.openGroup(""species"")); + char name_C[32 + 1]; + for (hsize_t idx(0); idx < spgroup.getNumObjs(); ++idx) + { + // const H5std_string name = spgroup.getObjnameByIdx(idx); + // H5::Group group(spgroup.openGroup(name.c_str())); + + memset(name_C, 0, 32 + 1); // clear buffer + H5Lget_name_by_idx(spgroup.getLocId(), ""."", H5_INDEX_NAME, H5_ITER_INC, + idx, name_C, 32, H5P_DEFAULT); + H5::Group group(spgroup.openGroup(name_C)); + const std::string name(name_C); + Species species(name); + + // const H5std_string serial = spgroup.getObjnameByIdx(idx); + // H5::Group group(spgroup.openGroup(serial.c_str())); + // Species species(std::string(serial.c_str())); + + traits_type::h5_species_struct property; + // group.openAttribute(""property"").read( + // traits_type::get_property_comp(), &property); + // group.openDataSet(""property"").read( + // &property, traits_type::get_property_comp()); + // H5::Attribute attr = group.openAttribute(""property""); + // H5::DataType dtype = attr.getDataType(); + // attr.read(dtype, &property); + + // group.openAttribute(""location"").read(H5::StrType(0, H5T_VARIABLE), + // property.location); //XXX: NEVER use ""&"" for H5std_string when + // reading. + group.openAttribute(""location"") + .read(H5::StrType(H5::PredType::C_S1, 32), property.location); + group.openAttribute(""is_structure"") + .read(H5::PredType::STD_I32LE, &property.is_structure); + + // std::cout << ""load_property("" << name << "","" << property.radius << + // "","" << property.D << "","" << property.location << "");"" << std::endl; + + struct_map.insert(std::make_pair(species, property)); + location_map.insert( + std::make_pair(std::string(property.location), species)); + // location_map.insert(std::make_pair(property.location, species)); + + H5::DataSet voxel_dset(group.openDataSet(""voxels"")); + const unsigned int num_voxels( + voxel_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr h5_voxel_array( + new traits_type::h5_voxel_struct[num_voxels]); + voxel_dset.read(h5_voxel_array.get(), traits_type::get_voxel_comp()); + voxel_dset.close(); + group.close(); + + std::vector> voxels; + for (unsigned int idx(0); idx < num_voxels; ++idx) + { + voxels.push_back(std::make_pair( + ParticleID(std::make_pair(h5_voxel_array[idx].lot, + h5_voxel_array[idx].serial)), + h5_voxel_array[idx].coordinate)); + } + voxels_map.insert(std::make_pair(species, voxels)); + } + spgroup.close(); + + std::vector sp_list; + traits_type::sort_by_location(location_map, sp_list); + for (const auto &species : sp_list) + { + traits_type::h5_species_struct property( + (*struct_map.find(species)).second); + std::vector> voxels( + (*voxels_map.find(species)).second); + if (property.is_structure == 0) + space->make_molecular_type(species, std::string(property.location)); + else + space->make_structure_type(species, std::string(property.location)); + space->add_voxels(species, voxels); + } +} + +} // namespace ecell4 + +#endif /* ECELL4_LATTICE_SPACE_HDF5_WRITER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpaceHDF5Writer.hpp",".hpp","11092","273","#ifndef ECELL4_PARTICLE_SPACE_HDF5_WRITER_HPP +#define ECELL4_PARTICLE_SPACE_HDF5_WRITER_HPP + +#include + +#include +#include + +#include ""types.hpp"" +#include ""Species.hpp"" +#include ""Particle.hpp"" + +#include ""Space.hpp"" + + +namespace ecell4 +{ + +struct ParticleSpaceHDF5Traits +{ + typedef struct h5_species_struct { + uint32_t id; + char serial[32]; // species' serial may exceed the limit + } h5_species_struct; + + typedef struct h5_particle_struct { + int lot; + int serial; + uint32_t sid; + double posx; + double posy; + double posz; + double radius; + double D; + } h5_particle_struct; + + static H5::CompType get_particle_comp_type() + { + H5::CompType h5_particle_comp_type(sizeof(h5_particle_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(h5_particle_comp_type.getId(), #member,\ + HOFFSET(h5_particle_struct, member), type.getId()) + INSERT_MEMBER(lot, H5::PredType::NATIVE_INT); + INSERT_MEMBER(serial, H5::PredType::NATIVE_INT); + INSERT_MEMBER(sid, H5::PredType::STD_I32LE); + INSERT_MEMBER(posx, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(posy, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(posz, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(radius, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(D, H5::PredType::NATIVE_DOUBLE); +#undef INSERT_MEMBER + // h5_particle_comp_type.insertMember( + // std::string(""lot""), HOFFSET(h5_particle_struct, lot), + // H5::PredType::NATIVE_INT); + // h5_particle_comp_type.insertMember( + // std::string(""serial""), HOFFSET(h5_particle_struct, serial), + // H5::PredType::NATIVE_INT); + // h5_particle_comp_type.insertMember( + // std::string(""sid""), HOFFSET(h5_particle_struct, sid), + // H5::PredType::STD_I32LE); + // h5_particle_comp_type.insertMember( + // std::string(""posx""), HOFFSET(h5_particle_struct, posx), + // H5::PredType::NATIVE_DOUBLE); + // h5_particle_comp_type.insertMember( + // std::string(""posy""), HOFFSET(h5_particle_struct, posy), + // H5::PredType::NATIVE_DOUBLE); + // h5_particle_comp_type.insertMember( + // std::string(""posz""), HOFFSET(h5_particle_struct, posz), + // H5::PredType::NATIVE_DOUBLE); + // h5_particle_comp_type.insertMember( + // std::string(""radius""), HOFFSET(h5_particle_struct, radius), + // H5::PredType::NATIVE_DOUBLE); + // h5_particle_comp_type.insertMember( + // std::string(""D""), HOFFSET(h5_particle_struct, D), + // H5::PredType::NATIVE_DOUBLE); + return h5_particle_comp_type; + } + + static H5::CompType get_species_comp_type() + { + H5::CompType h5_species_comp_type(sizeof(h5_species_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(h5_species_comp_type.getId(), #member,\ + HOFFSET(h5_species_struct, member), type.getId()) + INSERT_MEMBER(id, H5::PredType::STD_I32LE); + INSERT_MEMBER(serial, H5::StrType(H5::PredType::C_S1, 32)); +#undef INSERT_MEMBER + // h5_species_comp_type.insertMember( + // std::string(""id""), HOFFSET(h5_species_struct, id), + // H5::PredType::STD_I32LE); + // h5_species_comp_type.insertMember( + // std::string(""serial""), HOFFSET(h5_species_struct, serial), + // H5::StrType(H5::PredType::C_S1, 32)); + return h5_species_comp_type; + } +}; + +template +void save_particle_space(const Tspace_& space, H5::Group* root) +{ + typedef ParticleSpaceHDF5Traits traits_type; + typedef typename traits_type::h5_species_struct h5_species_struct; + typedef typename traits_type::h5_particle_struct h5_particle_struct; + + typedef std::vector > + particle_container_type; + const particle_container_type& particles(space.list_particles()); + const unsigned int num_particles(particles.size()); + + std::vector species; + typedef std::unordered_map + species_id_map_type; + species_id_map_type species_id_map; + + std::unique_ptr + h5_particle_table(new h5_particle_struct[num_particles]); + for (unsigned int i(0); i < num_particles; ++i) + { + species_id_map_type::const_iterator + it(species_id_map.find(particles[i].second.species_serial())); + if (it == species_id_map.end()) + { + species.push_back(particles[i].second.species()); + it = species_id_map.insert( + std::make_pair(particles[i].second.species_serial(), + species.size())).first; + } + + h5_particle_table[i].lot = particles[i].first.lot(); + h5_particle_table[i].serial = particles[i].first.serial(); + h5_particle_table[i].sid = (*it).second; + h5_particle_table[i].posx = particles[i].second.position()[0]; + h5_particle_table[i].posy = particles[i].second.position()[1]; + h5_particle_table[i].posz = particles[i].second.position()[2]; + h5_particle_table[i].radius = particles[i].second.radius(); + h5_particle_table[i].D = particles[i].second.D(); + } + + std::unique_ptr + h5_species_table(new h5_species_struct[species.size()]); + for (unsigned int i(0); i < species.size(); ++i) + { + h5_species_table[i].id = i + 1; + std::strcpy(h5_species_table[i].serial, + species[i].serial().c_str()); + } + + const int RANK = 1; + hsize_t dim1[] = {num_particles}; + H5::DataSpace dataspace1(RANK, dim1); + std::unique_ptr dataset1(new H5::DataSet( + root->createDataSet( + ""particles"", traits_type::get_particle_comp_type(), dataspace1))); + + hsize_t dim2[] = {species.size()}; + H5::DataSpace dataspace2(RANK, dim2); + std::unique_ptr dataset2(new H5::DataSet( + root->createDataSet( + ""species"", traits_type::get_species_comp_type(), dataspace2))); + + dataset1->write(h5_particle_table.get(), dataset1->getDataType()); + dataset2->write(h5_species_table.get(), dataset2->getDataType()); + + const uint32_t space_type = static_cast(Space::PARTICLE); + H5::Attribute attr_space_type( + root->createAttribute( + ""type"", H5::PredType::STD_I32LE, H5::DataSpace(H5S_SCALAR))); + attr_space_type.write(H5::PredType::STD_I32LE, &space_type); + + const double t = space.t(); + H5::Attribute attr_t( + root->createAttribute( + ""t"", H5::PredType::IEEE_F64LE, H5::DataSpace(H5S_SCALAR))); + attr_t.write(H5::PredType::IEEE_F64LE, &t); + + const Real3 edge_lengths = space.edge_lengths(); + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + H5::Attribute attr_lengths( + root->createAttribute( + ""edge_lengths"", lengths_type, H5::DataSpace(H5S_SCALAR))); + double lengths[] = {edge_lengths[0], edge_lengths[1], edge_lengths[2]}; + attr_lengths.write(lengths_type, lengths); +} + +template +void load_particle_space(const H5::Group& root, Tspace_* space) +{ + typedef ParticleSpaceHDF5Traits traits_type; + typedef typename traits_type::h5_species_struct h5_species_struct; + typedef typename traits_type::h5_particle_struct h5_particle_struct; + + Real3 edge_lengths; + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + root.openAttribute(""edge_lengths"").read(lengths_type, &edge_lengths); + space->reset(edge_lengths); + + double t; + root.openAttribute(""t"").read(H5::PredType::IEEE_F64LE, &t); + space->set_t(t); + + { + H5::DataSet species_dset(root.openDataSet(""species"")); + const unsigned int num_species( + species_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr h5_species_table( + new h5_species_struct[num_species]); + species_dset.read( + h5_species_table.get(), traits_type::get_species_comp_type()); + species_dset.close(); + + H5::DataSet particle_dset(root.openDataSet(""particles"")); + const unsigned int num_particles( + particle_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr h5_particle_table( + new h5_particle_struct[num_particles]); + particle_dset.read( + h5_particle_table.get(), traits_type::get_particle_comp_type()); + particle_dset.close(); + + typedef std::unordered_map + species_id_map_type; + species_id_map_type species_id_map; + for (unsigned int i(0); i < num_species; ++i) + { + species_id_map[h5_species_table[i].id] = h5_species_table[i].serial; + } + + for (unsigned int i(0); i < num_particles; ++i) + { + space->update_particle(ParticleID(std::make_pair(h5_particle_table[i].lot, h5_particle_table[i].serial)), Particle(Species(species_id_map[h5_particle_table[i].sid]), Real3(h5_particle_table[i].posx, h5_particle_table[i].posy, h5_particle_table[i].posz), h5_particle_table[i].radius, h5_particle_table[i].D)); + } + + // boost::scoped_array + // h5_particle_table(new h5_particle_struct[num_particles]); + // for (unsigned int i(0); i < num_particles; ++i) + // { + // species_id_map_type::const_iterator + // it(species_id_map.find(particles[i].second.species_serial())); + // if (it == species_id_map.end()) + // { + // species.push_back(particles[i].second.species()); + // it = species_id_map.insert( + // std::make_pair(particles[i].second.species_serial(), + // species.size())).first; + // } + + // h5_particle_table[i].lot = particles[i].first.lot(); + // h5_particle_table[i].serial = particles[i].first.serial(); + // h5_particle_table[i].sid = (*it).second; + // h5_particle_table[i].posx = particles[i].second.position()[0]; + // h5_particle_table[i].posy = particles[i].second.position()[1]; + // h5_particle_table[i].posz = particles[i].second.position()[2]; + // h5_particle_table[i].radius = particles[i].second.radius(); + // h5_particle_table[i].D = particles[i].second.D(); + // } + + // boost::scoped_array + // h5_species_table(new h5_species_struct[species.size()]); + // for (unsigned int i(0); i < species.size(); ++i) + // { + // h5_species_table[i].id = i + 1; + // std::strcpy(h5_species_table[i].serial, + // species[i].serial().c_str()); + // } + } +} + +} // ecell4 + +#endif /* ECELL4_PARTICLE_SPACE_HDF5_WRITER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Integer3.cpp",".cpp","1032","66","#include ""Integer3.hpp"" + +namespace ecell4 { + +Integer3& Integer3::operator+=(const Integer3& rhs) +{ + *this = add(*this, rhs); + return *this; +} + +Integer3& Integer3::operator-=(const Integer3& rhs) +{ + *this = subtract(*this, rhs); + return *this; +} + +Integer3& Integer3::operator*=(const Integer3::value_type& rhs) +{ + *this = multiply(*this, rhs); + return *this; +} + +Integer3 Integer3::east() const +{ + Integer3 retval(*this); + retval.col += 1; + return retval; +} + +Integer3 Integer3::west() const +{ + Integer3 retval(*this); + retval.col -= 1; + return retval; +} + +Integer3 Integer3::south() const +{ + Integer3 retval(*this); + retval.row += 1; + return retval; +} + +Integer3 Integer3::north() const +{ + Integer3 retval(*this); + retval.row -= 1; + return retval; +} + +Integer3 Integer3::dorsal() const +{ + Integer3 retval(*this); + retval.layer += 1; + return retval; +} + +Integer3 Integer3::ventral() const +{ + Integer3 retval(*this); + retval.layer -= 1; + return retval; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Context.hpp",".hpp","13622","533","#ifndef ECELL4_CONTEXT_HPP +#define ECELL4_CONTEXT_HPP + +#include ""UnitSpecies.hpp"" +#include ""Species.hpp"" +#include ""ReactionRule.hpp"" +#include +#include + +namespace ecell4 +{ + +namespace context +{ + +inline bool is_empty(const std::string& name) +{ + return name == """"; +} + +inline bool is_wildcard(const std::string& name) +{ + return (name.size() > 0 && name[0] == '_'); +} + +inline bool is_unnamed_wildcard(const std::string& name) +{ + return name == ""_""; +} + +inline bool is_pass_wildcard(const std::string& name) +{ + return name == ""_0""; +} + +inline bool is_named_wildcard(const std::string& name) +{ + return (name.size() > 1 && name[0] == '_' && !is_pass_wildcard(name)); +} + +Species format_species(const Species& sp); + +inline Species::serial_type unique_serial(const Species& sp) +{ + return format_species(sp).serial(); +} + +template +class rule_based_expression_matcher {}; + +template <> +class rule_based_expression_matcher +{ +public: + + typedef UnitSpecies value_type; + + typedef struct + { + typedef std::vector + iterator_container_type; + typedef std::unordered_map + variable_container_type; + + iterator_container_type iterators; + variable_container_type locals; + variable_container_type globals; + } context_type; + +public: + + rule_based_expression_matcher(const value_type& pttrn) + : pttrn_(pttrn) + { + ; + } + + boost::optional match(const value_type& another) + { + return match(another, context_type()); + } + + boost::optional match(const value_type& another, const context_type& ctx) + { + // another_ = another; + ctx_ = ctx; + + if (const boost::optional retval = match_unit_species(pttrn_, another, ctx)) + { + return retval; + } + + return boost::none; + } + + boost::optional next() + { + return boost::none; + } + + const context_type& context() const + { + return ctx_; + } + +protected: + + static boost::optional match_unit_species( + const UnitSpecies& pttrn, const UnitSpecies& usp, const context_type& org); + +protected: + + value_type pttrn_; + // value_type another_; + context_type ctx_; +}; + +template <> +class rule_based_expression_matcher > +{ +public: + + typedef std::vector value_type; + typedef rule_based_expression_matcher submatcher_type; + + typedef submatcher_type::context_type context_type; + +public: + + rule_based_expression_matcher(const value_type& pttrn) + { + matchers_.clear(); + for (value_type::const_iterator i(pttrn.begin()); + i != pttrn.end(); ++i) + { + matchers_.push_back(submatcher_type(*i)); + } + } + + boost::optional match(const value_type& another) + { + context_type::variable_container_type globals; + return match(another, globals); + } + + boost::optional match( + const value_type& another, const context_type::variable_container_type& globals) + { + another_ = another; + context_type ctx; + ctx.globals = globals; + return advance(0, 0, ctx); + } + + boost::optional next() + { + if (matchers_.size() == 0) + { + return context_type(); + } + return __next(); + } + + Integer count(const value_type& another) + { + context_type::variable_container_type globals; + + std::vector results; + boost::optional ctx = match(another, globals); + + if (!ctx) + { + return 0; + } + results.push_back(ctx.get().iterators); + std::sort(results.back().begin(), results.back().end()); + + while((ctx = next())) + { + results.push_back(ctx.get().iterators); + std::sort(results.back().begin(), results.back().end()); + } + + return static_cast(std::distance(results.begin(), std::unique(results.begin(), results.end()))); + + // if (!match(another, globals)) + // { + // return 0; + // } + + // Integer n(1); + // while (next()) + // { + // ++n; + // } + // return n; + } + + // const context_type& context() const + // { + // return ctx_; + // } + +protected: + + boost::optional __next() + { + //XXX: Make sure match was already called.. + size_t src = matchers_.size(); + while (src > 0) + { + --src; + + submatcher_type& matcher_at_src(matchers_[src]); + const size_t dst = iterators_[src]; + if (const boost::optional res = this->advance(src, dst + 1, matcher_at_src.context())) + { + return res; + } + } + return boost::none; + } + + boost::optional advance(const size_t src, const size_t dst, const context_type& ctx) + { + if (src == matchers_.size()) + { + iterators_ = ctx.iterators; + return ctx; + } + else if (dst == another_.size()) + { + return boost::none; + } + else if (std::find(ctx.iterators.begin(), ctx.iterators.end(), dst) + != ctx.iterators.end()) + { + return this->advance(src, dst + 1, ctx); + } + + submatcher_type& matcher_at_src(matchers_[src]); + boost::optional res = matcher_at_src.match(another_[dst], ctx); + if (res) + { + (*res).iterators.push_back(dst); + + if (const boost::optional newres = this->advance(src + 1, 0, (*res))) + { + return newres; + } + } + return this->advance(src, dst + 1, ctx); + } + +protected: + + value_type another_; + std::vector matchers_; + context_type::iterator_container_type iterators_; +}; + +template <> +class rule_based_expression_matcher +{ +public: + + typedef Species value_type; + typedef rule_based_expression_matcher > base_type; + typedef base_type::context_type context_type; + + rule_based_expression_matcher(const value_type& pttrn) + : base_(pttrn.units()) + { + ; + } + + boost::optional match(const value_type& another) + { + return base_.match(another.units()); + } + + boost::optional match( + const value_type& another, const context_type::variable_container_type& globals) + { + return base_.match(another.units(), globals); + } + + boost::optional next() + { + return base_.next(); + } + + size_t count(const value_type& another) + { + return base_.count(another.units()); + } + + // const context_type& context() const + // { + // return base_.context(); + // } + +protected: + + base_type base_; +}; + +template <> +class rule_based_expression_matcher > +{ +public: + + typedef std::vector value_type; + typedef rule_based_expression_matcher submatcher_type; + typedef submatcher_type::context_type context_type; + +public: + + rule_based_expression_matcher(const value_type& pttrn) + { + matchers_.clear(); + for (value_type::const_iterator i(pttrn.begin()); i != pttrn.end(); ++i) + { + matchers_.push_back(submatcher_type(*i)); + } + + iterators_.resize(matchers_.size()); + // contexts_.resize(matchers_.size()); + } + + boost::optional match(const value_type& another) + { + return __match(another); + } + + boost::optional match( + const value_type& another, const context_type::variable_container_type& globals) + { + //XXX: Not implemented yet + return __match(another); + } + + boost::optional next() + { + //XXX: Make sure match was already called.. + size_t pos = matchers_.size(); + while (pos > 0) + { + --pos; + + submatcher_type& matcher_at_pos(matchers_[pos]); + while (const boost::optional res = matcher_at_pos.next()) + { + // contexts_[pos] = (*res); + iterators_[pos] = (*res).iterators; + if (const boost::optional newres = this->advance(pos + 1, (*res).globals)) + { + return newres; + } + } + } + return boost::none; + } + + //TODO: HERE + context_type context() const + { + context_type ctx; + if (matchers_.size() == 0) + { + return ctx; + } + + // ctx.globals = contexts_.back().globals; + ctx.globals = globals_; + + std::vector strides; + strides.reserve(another_.size()); + { + unsigned int stride = 0; + for (value_type::const_iterator i(another_.begin()); i != another_.end(); ++i) + { + strides.push_back(stride); + stride += (*i).units().size(); + } + } + + for (std::vector::const_iterator + i(matchers_.begin()); i != matchers_.end(); ++i) + { + const unsigned int idx1 = std::distance(matchers_.begin(), i); // a position in matcher_ + const unsigned int idx2 = permutation_[idx1]; // a position in reactants + const unsigned int stride = strides[idx2]; + // const context_type& ctx_at_idx1 = contexts_[idx1]; + const context_type::iterator_container_type& it = iterators_[idx1]; + + // for (context_type::iterator_container_type::const_iterator + // j(ctx_at_idx1.iterators.begin()); + // j != ctx_at_idx1.iterators.end(); ++j) + for (context_type::iterator_container_type::const_iterator + j(it.begin()); j != it.end(); ++j) + { + // // a position in context.iterators + // const unsigned int idx3 = std::distance((*i).context().iterators.begin(), j); + const unsigned int idx4 = (*j); // a position in units of a Species + + ctx.iterators.push_back(idx4 + stride); + } + } + + return ctx; + } + //TODO: THERE + +protected: + + typedef std::vector permutation_type; + + boost::optional __match(const value_type& another) + { + permutation_type permutation; + permutation.reserve(matchers_.size()); + for (size_t i(0); i != matchers_.size(); ++i) + { + permutation.push_back(i); + } + return __match(another, permutation); + } + + boost::optional __match(const value_type& another, const permutation_type& permutation) + { + assert(matchers_.size() < 3); + assert(matchers_.size() == permutation.size()); + + another_ = another; //XXX: copy? + permutation_ = permutation; + + if (matchers_.size() != another.size()) + { + return boost::none; + } + + context_type::variable_container_type globals; + return this->advance(0, globals); + } + + boost::optional advance(const size_t pos, const context_type::variable_container_type& globals) + { + if (pos == matchers_.size()) + { + globals_ = globals; + return this->context(); + } + + submatcher_type& matcher_at_pos(matchers_[pos]); + const value_type::value_type& another_at_pos(another_[pos]); + for (boost::optional res = matcher_at_pos.match(another_at_pos, globals); + res; res = matcher_at_pos.next()) + { + // contexts_[pos] = (*res); + iterators_[pos] = (*res).iterators; + if (const boost::optional newres = this->advance(pos + 1, (*res).globals)) + { + return newres; + } + } + return boost::none; + } + +protected: + + // value_type pttrn_; + value_type another_; + permutation_type permutation_; + + std::vector matchers_; + + // std::vector contexts_; + std::vector iterators_; + context_type::variable_container_type globals_; +}; + +} // context + +/** + * New interfaces for the rule-based modeling + */ + +inline Integer count_species_matches(const Species& pttrn, const Species& sp) +{ + return static_cast( + context::rule_based_expression_matcher(pttrn).count(sp)); +} + +inline Species format_species(const Species& sp) +{ + return context::format_species(sp); +} + +struct SpeciesExpressionMatcher +{ + context::rule_based_expression_matcher pttrn; + + SpeciesExpressionMatcher(const Species& pttrn) + : pttrn(pttrn) + { + ; + } + + bool match(const Species& sp) + { + return (pttrn.match(sp) ? true : false); + } + + // bool next() + // { + // return (pttrn.next() ? true : false); + // } + + size_t count(const Species& sp) + { + return pttrn.count(sp); + } +}; + +std::vector generate_reaction_rules( + const ReactionRule& pttrn, + const ReactionRule::reactant_container_type& reactants); + +} // ecell4 + +#endif /* ECELL4_CONTEXT_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/NetworkModel.cpp",".cpp","9157","291","#include + +#include ""exceptions.hpp"" +#include ""NetworkModel.hpp"" + + +namespace ecell4 +{ + +bool NetworkModel::update_species_attribute(const Species& sp) +{ + species_container_type::iterator i(std::find(species_attributes_.begin(), species_attributes_.end(), sp)); + if (i == species_attributes_.end()) + { + add_species_attribute(sp); + return true; + } + (*i).overwrite_attributes(sp); + return false; +} + +void NetworkModel::add_species_attribute(const Species& sp, const bool proceed) +{ + species_attributes_.push_back(sp); + species_attributes_proceed_.push_back(proceed); +} + +void NetworkModel::remove_species_attribute(const Species& sp) +{ + species_container_type::iterator i(std::find(species_attributes_.begin(), species_attributes_.end(), sp)); + if (i == species_attributes_.end()) + { + throw_exception(""The given Speices ["", sp.serial(), ""] was not found""); + } + species_attributes_proceed_.erase( + species_attributes_proceed_.begin() + std::distance(species_attributes_.begin(), i)); + species_attributes_.erase(i); +} + +bool NetworkModel::has_species_attribute(const Species& sp) const +{ + species_container_type::const_iterator i( + std::find(species_attributes_.begin(), species_attributes_.end(), sp)); + return (i != species_attributes_.end()); +} + +Species NetworkModel::apply_species_attributes(const Species& sp) const +{ + Species ret(sp); + species_container_type::const_iterator i(species_attributes_.begin()); + std::vector::const_iterator j(species_attributes_proceed_.begin()); + for (; i != species_attributes_.end() && j != species_attributes_proceed_.end(); ++i, ++j) + { + if ((*i).serial() != ""_"" && sp != (*i)) + { + continue; + } + ret.overwrite_attributes(*i); + if (!(*j)) + { + break; + } + } + return ret; +} + +Integer NetworkModel::apply(const Species& pttrn, const Species& sp) const +{ + return (pttrn == sp ? 1 : 0); +} + +std::vector NetworkModel::query_reaction_rules( + const Species& sp) const +{ + first_order_reaction_rules_map_type::const_iterator + i(first_order_reaction_rules_map_.find(sp.serial())); + + std::vector retval; + if (i != first_order_reaction_rules_map_.end()) + { + retval.reserve((*i).second.size()); + for (first_order_reaction_rules_map_type::mapped_type::const_iterator + j((*i).second.begin()); j != (*i).second.end(); ++j) + { + retval.push_back(reaction_rules_[*j]); + } + } + return retval; +} + +std::vector NetworkModel::query_reaction_rules( + const Species& sp1, const Species& sp2) const +{ + std::vector retval; + const std::pair + key(sp1.serial() < sp2.serial()? + std::make_pair(sp1.serial(), sp2.serial()): + std::make_pair(sp2.serial(), sp1.serial())); + + second_order_reaction_rules_map_type::const_iterator + i(second_order_reaction_rules_map_.find(key)); + if (i != second_order_reaction_rules_map_.end()) + { + retval.reserve((*i).second.size()); + for (second_order_reaction_rules_map_type::mapped_type::const_iterator + j((*i).second.begin()); j != (*i).second.end(); ++j) + { + retval.push_back(reaction_rules_[*j]); + } + } + return retval; +} + +std::vector NetworkModel::apply( + const ReactionRule& rr, const ReactionRule::reactant_container_type& reactants) const +{ + if (rr.reactants().size() != reactants.size()) + { + return std::vector(); + } + + ReactionRule::reactant_container_type::const_iterator + i(rr.reactants().begin()), j(reactants.begin()); + for (; i != rr.reactants().end(); ++i, ++j) + { + if (*i != *j) + { + return std::vector(); + } + } + return std::vector(1, rr); +} + +void NetworkModel::add_reaction_rule(const ReactionRule& rr) +{ + if (rr.has_descriptor()) + { + reaction_rules_.push_back(rr); + return; + } + + for (reaction_rule_container_type::iterator i(reaction_rules_.begin()); + i != reaction_rules_.end(); ++i) + { + if ((*i) == rr && !(*i).has_descriptor()) + { + (*i).set_k((*i).k() + rr.k()); // Merging + return; + } + } + + const reaction_rule_container_type::size_type idx(reaction_rules_.size()); + reaction_rules_.push_back(rr); + + if (rr.reactants().size() == 1) + { + const Species::serial_type key = rr.reactants()[0].serial(); + first_order_reaction_rules_map_[key].push_back(idx); + } + else if (rr.reactants().size() == 2) + { + const Species::serial_type + serial1(rr.reactants()[0].serial()), + serial2(rr.reactants()[1].serial()); + const std::pair + key(serial1 < serial2? + std::make_pair(serial1, serial2): + std::make_pair(serial2, serial1)); + second_order_reaction_rules_map_[key].push_back(idx); + } + else + { + ; // do nothing + } +} + +void NetworkModel::remove_reaction_rule(const ReactionRule& rr) +{ + reaction_rule_container_type::size_type removed = 0; + while (true) + { + reaction_rule_container_type::iterator + i(std::find(reaction_rules_.begin(), reaction_rules_.end(), rr)); + if (i == reaction_rules_.end()) + { + break; + } + remove_reaction_rule(i); + ++removed; + } + + if (removed == 0) + { + throw NotFound(""The given reaction rule was not found.""); + } +} + +void NetworkModel::remove_reaction_rule(const NetworkModel::reaction_rule_container_type::iterator i) +{ + assert(reaction_rules_.size() > 0); + const reaction_rule_container_type::size_type idx = i - reaction_rules_.begin(); + assert(idx < reaction_rules_.size()); + const reaction_rule_container_type::size_type last_idx(reaction_rules_.size() - 1); + + { + const ReactionRule& rr = reaction_rules_[idx]; + + if (rr.has_descriptor()) + { + ; // do nothing + } + else if (rr.reactants().size() == 1) + { + first_order_reaction_rules_map_type::iterator + j(first_order_reaction_rules_map_.find(rr.reactants()[0].serial())); + assert(j != first_order_reaction_rules_map_.end()); + + first_order_reaction_rules_map_type::mapped_type::iterator + k(std::remove((*j).second.begin(), (*j).second.end(), idx)); + assert(k != (*j).second.end()); + + (*j).second.erase(k, (*j).second.end()); + } + else if (rr.reactants().size() == 2) + { + second_order_reaction_rules_map_type::iterator + j(second_order_reaction_rules_map_.find(std::make_pair( + rr.reactants()[0].serial(), rr.reactants()[1].serial()))); + assert(j != second_order_reaction_rules_map_.end()); + + second_order_reaction_rules_map_type::mapped_type::iterator + k(std::remove((*j).second.begin(), (*j).second.end(), idx)); + assert(k != (*j).second.end()); + + (*j).second.erase(k, (*j).second.end()); + } + } + + if (idx < last_idx) + { + reaction_rule_container_type::value_type const + rrlast(reaction_rules_[last_idx]); + (*i) = rrlast; + + if (rrlast.has_descriptor()) + { + ; // do nothing + } + else if (rrlast.reactants().size() == 1) + { + first_order_reaction_rules_map_type::iterator + j(first_order_reaction_rules_map_.find( + rrlast.reactants()[0].serial())); + assert(j != first_order_reaction_rules_map_.end()); + + first_order_reaction_rules_map_type::mapped_type::iterator + k(std::remove((*j).second.begin(), (*j).second.end(), last_idx)); + assert(k != (*j).second.end()); + + (*j).second.erase(k, (*j).second.end()); + (*j).second.push_back(idx); + } + else if (rrlast.reactants().size() == 2) + { + second_order_reaction_rules_map_type::iterator + j(second_order_reaction_rules_map_.find(std::make_pair( + rrlast.reactants()[0].serial(), + rrlast.reactants()[1].serial()))); + assert(j != second_order_reaction_rules_map_.end()); + + second_order_reaction_rules_map_type::mapped_type::iterator + k(std::remove((*j).second.begin(), (*j).second.end(), last_idx)); + assert(k != (*j).second.end()); + + (*j).second.erase(k, (*j).second.end()); + (*j).second.push_back(idx); + } + } + + reaction_rules_.pop_back(); +} + +bool NetworkModel::has_reaction_rule(const ReactionRule& rr) const +{ + reaction_rule_container_type::const_iterator + i(std::find(reaction_rules_.begin(), reaction_rules_.end(), rr)); + return (i != reaction_rules_.end()); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Barycentric.cpp",".cpp","5150","175","#include ""Barycentric.hpp"" + +namespace ecell4 +{ + +namespace detail +{ + +// static inline Real cross_section(const Barycentric& pos, +// const Barycentric& displacement, +// const std::size_t edge_idx) +// { +// const std::size_t idx = (edge_idx==0) ? 2 : edge_idx-1; +// return -pos[idx] / displacement[idx]; +// } + +static inline Real triangle_area_2D(const Real x1, const Real y1, + const Real x2, const Real y2, + const Real x3, const Real y3) +{ + return (x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2); +} + +} // detail + +std::pair +first_cross_edge(const Barycentric& pos, const Barycentric& disp) +{ + Barycentric npos = pos + disp; + if(std::abs(npos[0]) < 1e-10){npos[0] = 0.0;} + if(std::abs(npos[1]) < 1e-10){npos[1] = 0.0;} + if(std::abs(npos[2]) < 1e-10){npos[2] = 0.0;} + + const Real multiply = npos[0] * npos[1] * npos[2]; + if(multiply < 0.) // (+, +, -) or one of its permutations + { + if (npos[0] < 0.0 && npos[1] > 0.0 && npos[2] > 0.0) + { + return std::make_pair(1, -pos[0] / disp[0]); + } + else if(npos[0] > 0.0 && npos[1] < 0.0 && npos[2] > 0.0) + { + return std::make_pair(2, -pos[1] / disp[1]); + } + else if(npos[0] > 0.0 && npos[1] > 0.0 && npos[2] < 0.0) + { + return std::make_pair(0, -pos[2] / disp[2]); + } + else + { + std::cerr << ""pos = "" << pos << std::endl; + std::cerr << ""disp = "" << disp << std::endl; + std::cerr << ""npos = "" << npos << std::endl; + throw std::logic_error(""Polygon::cross_edge: never reach here""); + } + } + else if(multiply == 0.0) // include 0. already on the edge. + { + if (npos[0] == 0.0) {return std::make_pair(1, 1.0);} + else if(npos[1] == 0.0) {return std::make_pair(2, 1.0);} + else if(npos[2] == 0.0) {return std::make_pair(0, 1.0);} + } + else // (+, -, -) or one of its permutations + { + if(npos[0] > 0.0 && npos[1] > 0.0 && npos[2] > 0.0) // (+, +, +) case + { + throw std::invalid_argument(""BDPolygon::cross_edge""); + } + + if(npos[0] > 0.) + { + const Real ab = -pos[2] / disp[2]; + const Real ca = -pos[1] / disp[1]; + return (ab > ca) ? std::make_pair(2, ca) : std::make_pair(0, ab); + } + else if(npos[1] > 0.) + { + const Real ab = -pos[2] / disp[2]; + const Real bc = -pos[0] / disp[0]; + return (bc > ab) ? std::make_pair(0, ab) : std::make_pair(1, bc); + } + else // if(npos[2] > 0.) + { + const Real bc = -pos[0] / disp[0]; + const Real ca = -pos[1] / disp[1]; + return (ca > bc) ? std::make_pair(1, bc) : std::make_pair(2, ca); + } + } + throw std::logic_error(""never reach here""); // to supress warning message +} + +Barycentric force_put_inside(const Barycentric& bary) +{ + if(!on_plane(bary)) + { + throw std::invalid_argument(""force_put_inside: outside of the plane""); + } + if(is_inside(bary)) + { + return bary; + } + + Barycentric retval(bary); + std::array over; + over[0] = over[1] = over[2] = false; + for(std::size_t i=0; i<3; ++i) + { + if(retval[i] < 0.) + { + over[i] = true; + retval[i] = 0; + } + else if(retval[i] > 1.) + { + over[i] = true; + retval[i] = 1.; + } + } + if(!over[0]) + { + retval[0] = 1. - retval[1] - retval[2]; + } + else if(!over[1]) + { + retval[1] = 1. - retval[0] - retval[2]; + } + else if(!over[2]) + { + retval[2] = 1. - retval[0] - retval[1]; + } + else + { + throw std::invalid_argument(""force_put_inside: too far""); + } + return retval; +} + +Barycentric to_barycentric(const Real3& pos, const Triangle& face) +{ + const Real3& a = face.vertex_at(0); + const Real3& b = face.vertex_at(1); + const Real3& c = face.vertex_at(2); + const Real3 m = cross_product(face.edge_at(0), face.edge_at(2)) * (-1.); + const Real x = std::abs(m[0]); + const Real y = std::abs(m[1]); + const Real z = std::abs(m[2]); + + Real nu, nv, ood; + if(x >= y && x >= z) + { + nu = detail::triangle_area_2D(pos[1], pos[2], b[1], b[2], c[1], c[2]); + nv = detail::triangle_area_2D(pos[1], pos[2], c[1], c[2], a[1], a[2]); + ood = 1.0 / m[0]; + } + else if(y >= x && y >= z) + { + nu = detail::triangle_area_2D(pos[0], pos[2], b[0], b[2], c[0], c[2]); + nv = detail::triangle_area_2D(pos[0], pos[2], c[0], c[2], a[0], a[2]); + ood = 1.0 / -m[1]; + } + else + { + nu = detail::triangle_area_2D(pos[0], pos[1], b[0], b[1], c[0], c[1]); + nv = detail::triangle_area_2D(pos[0], pos[1], c[0], c[1], a[0], a[1]); + ood = 1.0 / m[2]; + } + Barycentric bary; + bary[0] = nu * ood; + bary[1] = nv * ood; + bary[2] = 1.0 - bary[0] - bary[1]; + return bary; +} + +}// ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ObjectIDContainer.hpp",".hpp","6627","194","#ifndef ECELL4_CORE_OBJECT_ID_CONTAINER_HPP +#define ECELL4_CORE_OBJECT_ID_CONTAINER_HPP +#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +// +// A container that combines map and vector<{id, object}>. +// It does not check collision or any other kind of object dependent tests, +// but encapsulates relationships between id-idx map and a vector. +// +template +class ObjectIDContainer +{ +public: + using identifier_type = Tid; + using object_type = Tobject; + using self_type = ObjectIDContainer; + using id_idx_map_type = std::unordered_map; + using value_type = std::pair; + using container_type = std::vector; + using size_type = typename container_type::size_type; + using difference_type = typename container_type::difference_type; + using iterator = typename container_type::iterator; + using const_iterator = typename container_type::const_iterator; + +public: + + ObjectIDContainer() = default; + ~ObjectIDContainer() = default; + ObjectIDContainer(const ObjectIDContainer&) = default; + ObjectIDContainer(ObjectIDContainer&&) = default; + ObjectIDContainer& operator=(const ObjectIDContainer&) = default; + ObjectIDContainer& operator=(ObjectIDContainer&&) = default; + + bool update(const identifier_type& id, const object_type& obj) + { + const auto found(this->idxmap_.find(id)); + if(found == this->idxmap_.end()) + { + idxmap_[id] = this->objects_.size(); + objects_.emplace_back(id, obj); + return true; + } + else + { + objects_[found->second] = std::make_pair(id, obj); + return false; + } + } + + void remove(const identifier_type& id) + { + const auto found(this->idxmap_.find(id)); + if(found == this->idxmap_.end()) + { + throw_exception(utils::type_name_of::value(), + ""::remove(id="", id, ""): object not found""); + } + + const size_type idx(found->second), last(objects_.size()-1); + if(idx != last) + { + idxmap_[objects_[last].first] = idx; + objects_[idx] = std::move(objects_[last]); + } + objects_.pop_back(); + idxmap_.erase(id); + return; + } + + std::pair get(const identifier_type& id) const + { + const auto found(this->idxmap_.find(id)); + if(found == this->idxmap_.end()) + { + throw_exception(utils::type_name_of::value(), + ""::get(id="", id, ""): object not found""); + } + return objects_[found->second]; + } + + bool has(const identifier_type& id) const {return idxmap_.count(id) != 0;} + container_type const& list() const noexcept {return objects_;} + + void clear() + { + idxmap_ .clear(); + objects_.clear(); + return; + } + + std::size_t size() const noexcept {return objects_.size();} + bool empty() const noexcept {return objects_.empty();} + + bool diagnosis() const + { + for(const auto& item : this->idxmap_) + { + const auto& id = item.first; + const auto& idx = item.second; + + identifier_type id_by_cont; + try + { + id_by_cont = objects_.at(idx).first; + } + catch(std::out_of_range& oor) + { + throw_exception(utils::type_name_of::value(), + ""::diagnosis: object(id="", id, "") not found in the container""); + } + if(id_by_cont != id) + { + throw_exception(utils::type_name_of::value(), + ""::diagnosis: object(id="", id, "") index is invalid: "", idx, + ""-th object has id "", id_by_cont); + } + } + for(std::size_t i=0; iidxmap_.count(id) == 0) + { + throw_exception(utils::type_name_of::value(), + ""::diagnosis: object(id="", id, "") not found in idxmap""); + } + if(this->idxmap_.at(id) != i) + { + throw_exception(utils::type_name_of::value(), + ""::diagnosis: object(id="", id, "") has different idx ("", idxmap_.at(id), + "") in idxmap""); + } + } + return true; + } + + value_type& at(const identifier_type& id) + { + const auto found(idxmap_.find(id)); + if(found == idxmap_.end()) + { + throw_exception(utils::type_name_of::value(), + ""::at(id="", id, ""): object not found""); + } + return objects_.at(found->second); + } + value_type const& at(const identifier_type& id) const + { + const auto found(idxmap_.find(id)); + if(found == idxmap_.end()) + { + throw_exception(utils::type_name_of::value(), + ""::at(id="", id, ""): object not found""); + } + return objects_.at(found->second); + } + + value_type& operator[](const identifier_type& id) + { + return objects_[idxmap_[id]]; + } + value_type const& operator[](const identifier_type& id) const + { + return objects_[idxmap_[id]]; + } + + value_type const& front() const noexcept {return objects_.front();} + value_type& front() noexcept {return objects_.front();} + value_type const& back() const noexcept {return objects_.back();} + value_type& back() noexcept {return objects_.back();} + + iterator begin() noexcept {return objects_.begin();} + iterator end() noexcept {return objects_.end();} + const_iterator begin() const noexcept {return objects_.begin();} + const_iterator end() const noexcept {return objects_.end();} + const_iterator cbegin() const noexcept {return objects_.begin();} + const_iterator cend() const noexcept {return objects_.end();} + +private: + + id_idx_map_type idxmap_; + container_type objects_; +}; +} // ecell4 +#endif// ECELL4_OBJECT_ID_CONTAINER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/NetfreeModel.hpp",".hpp","3781","141","#ifndef ECELL4_NETFREE_MODEL_HPP +#define ECELL4_NETFREE_MODEL_HPP + +#include +#include +#include +#include +#include + +#include ""types.hpp"" +#include ""Species.hpp"" +#include ""ReactionRule.hpp"" +#include ""Model.hpp"" + +#include ""Context.hpp"" +#include ""NetworkModel.hpp"" + + +namespace ecell4 +{ + +class NetfreeModel + : public Model +{ +public: + + typedef Model base_type; + typedef base_type::species_container_type species_container_type; + typedef base_type::reaction_rule_container_type reaction_rule_container_type; + +public: + + NetfreeModel() + : base_type(), species_attributes_(), species_attributes_proceed_(), reaction_rules_(), effective_(false) + { + ; + } + + virtual ~NetfreeModel() + { + ; + } + + // ModelTraits + + std::vector query_reaction_rules(const Species& sp) const; + std::vector query_reaction_rules( + const Species& sp1, const Species& sp2) const; + + std::vector query_reaction_rules( + const std::vector& splist, const std::vector::size_type n) const; + + inline std::vector query_reaction_rules( + const std::vector& reactants) const + { + return this->query_reaction_rules(reactants, reactants.size()); + } + + Integer apply(const Species& pttrn, const Species& sp) const; + std::vector apply( + const ReactionRule& rr, + const ReactionRule::reactant_container_type& reactants) const; + + Species apply_species_attributes(const Species& sp) const; + + // NetfreeModelTraits + + bool update_species_attribute(const Species& sp); + void add_species_attribute(const Species& sp, const bool proceed = false); + bool has_species_attribute(const Species& sp) const; + bool has_species_attribute_exact(const Species& sp) const; + void remove_species_attribute(const Species& sp); + + void add_reaction_rule(const ReactionRule& rr); + void remove_reaction_rule(const ReactionRule& rr); + bool has_reaction_rule(const ReactionRule& rr) const; + + const species_container_type& species_attributes() const + { + return species_attributes_; + } + + const std::vector& species_attributes_proceed() const + { + return species_attributes_proceed_; + } + + const reaction_rule_container_type& reaction_rules() const + { + return reaction_rules_; + } + + // Optional functions + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr, + const std::map& max_stoich) const; + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr) const; + std::shared_ptr expand(const std::vector& sp) const; + + void set_effective(const bool effective) + { + effective_ = effective; + } + + const bool effective() const + { + return effective_; + } + +protected: + + species_container_type species_attributes_; + std::vector species_attributes_proceed_; //XXX: + reaction_rule_container_type reaction_rules_; + + bool effective_; +}; + +namespace extras +{ + +std::pair, bool> generate_network_from_netfree_model( + const NetfreeModel& nfm, const std::vector& seeds, const Integer max_itr, + const std::map& max_stoich); + +inline std::pair, bool> generate_network_from_netfree_model( + const NetfreeModel& nfm, const std::vector& seeds, const Integer max_itr) +{ + const std::map max_stoich; + return generate_network_from_netfree_model( + nfm, seeds, max_itr, max_stoich); +} + +} // extras + +} // ecell4 + +#endif /* ECELL4_NETFREE_MODEL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/VacantType.hpp",".hpp","647","36","#ifndef ECELL4_VACANT_TYPE_HPP +#define ECELL4_VACANT_TYPE_HPP +#include ""StructureType.hpp"" +#include + +namespace ecell4 +{ + +class VacantType : public StructureType +{ +private: + typedef StructureType base_type; + + VacantType() : base_type(Species("""", 0, 0), std::weak_ptr()) + { + ; // do nothing + } + +public: + ~VacantType() + { + ; // do nothing + } + + voxel_type_type const voxel_type() const { return VACANT; } + + static std::shared_ptr allocate() + { + return std::shared_ptr(new VacantType()); + } +}; + +} // namespace ecell4 + +#endif /* ECELL4_VACANT_TYPE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Identifier.hpp",".hpp","5665","285","#ifndef ECELL4_IDENTIFIER_HPP +#define ECELL4_IDENTIFIER_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ + +struct DefaultLot +{ + DefaultLot& operator=(const DefaultLot&) + { + return *this; + } + + operator bool() const + { + return false; + } + + bool operator!() const + { + return true; + } + + DefaultLot& operator++() + { + return *this; + } + + DefaultLot operator++(int) + { + return DefaultLot(); + } + + DefaultLot& operator--() + { + return *this; + } + + DefaultLot operator--(int) + { + return DefaultLot(); + } + + bool operator==(const DefaultLot& rhs) const + { + return true; + } + + bool operator!=(const DefaultLot& rhs) const + { + return false; + } + + bool operator<(const DefaultLot& rhs) const + { + return false; + } + + bool operator>=(const DefaultLot& rhs) const + { + return false; + } + + bool operator>(const DefaultLot& rhs) const + { + return false; + } + + bool operator<=(const DefaultLot& rhs) const + { + return false; + } +}; + +template +inline std::basic_ostream& +operator<<(std::basic_ostream& strm, const DefaultLot&) +{ + strm << '0'; + return strm; +} + +template +struct Identifier +{ +public: + + typedef Tlot_ lot_type; + typedef Tserial_ serial_type; + typedef std::pair value_type; + +public: + + Identifier(const value_type& value) + : value_(value) + { + ; + } + + Tbase_ lot_add(const lot_type& rhs) const + { + return value_type(value_.first + rhs, value_.second); + } + + Tbase_ lot_subtract(const lot_type& rhs) const + { + return value_type(value_.first - rhs, value_.second); + } + + Tbase_& lot_advance(const lot_type& rhs) + { + value_.first += rhs; + return static_cast(*this); + } + + Tbase_& lot_retrace(const lot_type& rhs) + { + value_.first -= rhs; + return static_cast(*this); + } + + Tbase_ serial_add(const serial_type& rhs) const + { + return value_type(value_.first, value_.second + rhs); + } + + Tbase_ seral_subtract(const serial_type& rhs) const + { + return value_type(value_.first, value_.second - rhs); + } + + Tbase_& serial_advance(const serial_type& rhs) + { + value_.second += rhs; + return static_cast(*this); + } + + Tbase_& serial_retrace(const serial_type& rhs) + { + value_.second -= rhs; + return static_cast(*this); + } + + Tbase_& operator=(const Tbase_& rhs) + { + value_.first = rhs.value_.first; + value_.second = rhs.value_.second; + return (*reinterpret_cast(this)); + } + + // operator bool() const + // { + // return value_.second != 0; + // } + + // bool operator!() const + // { + // return value_.second == 0; + // } + + bool is_initialized() const + { + return value_.second != 0; + } + + bool operator==(const Tbase_& rhs) const + { + return value_.first == rhs.value_.first && + value_.second == rhs.value_.second; + } + + bool operator!=(const Tbase_& rhs) const + { + return value_.first != rhs.value_.first + || value_.second != rhs.value_.second; + } + + bool operator<(const Tbase_& rhs) const + { + return value_.second < rhs.value_.second + || (value_.second == rhs.value_.second && + value_.first < rhs.value_.first); + } + + bool operator>=(const Tbase_& rhs) const + { + return value_.second > rhs.value_.second + || (value_.second == rhs.value_.second && + value_.first >= rhs.value_.first); + } + + bool operator>(const Tbase_& rhs) const + { + return value_.second > rhs.value_.second + || (value_.second == rhs.value_.second && + value_.first > rhs.value_.first); + } + + bool operator<=(const Tbase_& rhs) const + { + return value_.second < rhs.value_.second + || (value_.second == rhs.value_.second && + value_.first <= rhs.value_.first); + } + + operator value_type() const + { + return value_; + } + + const value_type& operator()() const + { + return value_; + } + + lot_type& lot() + { + return value_.first; + } + + const lot_type& lot() const + { + return value_.first; + } + + serial_type& serial() + { + return value_.second; + } + + const serial_type& serial() const + { + return value_.second; + } + + value_type& operator()() + { + return value_; + } + +protected: + + value_type value_; +}; + +struct ParticleID: + public Identifier +{ + typedef Identifier base_type; + + ParticleID(const value_type& value = value_type(0, 0)) + : base_type(value) + { + ; + } +}; + +template +inline std::basic_ostream& operator<<(std::basic_ostream& strm, + const ParticleID& v) +{ + strm << ""PID("" << v().first << "":"" << v().second << "")""; + return strm; +} + +} // ecell4 + +namespace std{ +template<> +struct hash +{ + std::size_t operator()(const ecell4::ParticleID& val) const + { + return static_cast(val().first ^ val().second); + } +}; +} // std + +#endif /* ECELL4_IDENTIFIER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/SimulatorBase.hpp",".hpp","6641","266","#ifndef ECELL4_SIMULATOR_BASE_HPP +#define ECELL4_SIMULATOR_BASE_HPP + +#include + +#include ""Model.hpp"" +#include ""Simulator.hpp"" +#include ""EventScheduler.hpp"" +#include ""observers.hpp"" + + +namespace ecell4 +{ + +template +class SimulatorBase + : public Simulator +{ +public: + + typedef Tmodel_ model_type; + typedef Tworld_ world_type; + typedef SimulatorBase this_type; + +protected: + + struct ObserverEvent: Event + { + ObserverEvent( + this_type* sim, Observer* obs, const Real& t) + : Event(t), sim_(sim), obs_(obs), running_(true) + { + time_ = obs_->next_time(); + } + + virtual ~ObserverEvent() + { + ; + } + + virtual void fire() + { + const std::shared_ptr world = sim_->world(); + running_ = obs_->fire(sim_, world); + // running_ = obs_->fire(sim_, sim_->world()); + // running_ = obs_->fire(sim_, static_cast(sim_->world().get())); + time_ = obs_->next_time(); + } + + bool running() const + { + return running_; + } + + protected: + + this_type* sim_; + Observer* obs_; + bool running_; + }; + + struct observer_every + { + bool operator()(std::shared_ptr const& val) const + { + return val->every(); + } + }; + +public: + + SimulatorBase( + const std::shared_ptr& world, + const std::shared_ptr& model) + : world_(world), model_(model), num_steps_(0) + { + world_->bind_to(model_); + } + + SimulatorBase(const std::shared_ptr& world) + : world_(world), num_steps_(0) + { + std::cerr << ""WARNING: Using constructor is deprecated and will be removed."" + "" Give both World and Model."" << std::endl; + if (std::shared_ptr bound_model = world_->lock_model()) + { + model_ = bound_model; + } + else + { + throw std::invalid_argument(""A world must be bound to a model.""); + } + } + + virtual ~SimulatorBase() + { + ; // do nothing + } + + const std::shared_ptr& model() const + { + return model_; + } + + const std::shared_ptr& world() const + { + return world_; + } + + /** + * get the number of steps. + * @return the number of steps Integer + */ + Integer num_steps() const + { + return num_steps_; + } + + virtual Real t() const + { + return (*world_).t(); + } + + virtual void set_t(const Real& t) + { + (*world_).set_t(t); + } + + /** + * set step interval. + */ + virtual void set_dt(const Real& dt) + { + std::cerr << ""WARN: set_dt(const Real&) was just ignored."" << std::endl; + } + + void run(const Real& duration, const bool is_dirty=true) + { + if (is_dirty) + { + initialize(); + } + + const Real upto(t() + duration); + while (step(upto)) + { + ; // do nothing + } + } + + void run(const Real& duration, const std::shared_ptr& observer, const bool is_dirty=true) + { + std::vector > observers; + observers.push_back(observer); + run(duration, observers, is_dirty); + } + + bool fire_observers( + const std::vector >::iterator begin, + const std::vector >::iterator end) + { + bool retval = true; + for (std::vector >::iterator + i(begin); i != end; ++i) + { + // if (!(*i)->fire(this, static_cast(world_.get()))) + if (!(*i)->fire(this, world_)) + { + retval = false; + } + } + return retval; + } + + void run(const Real& duration, std::vector > observers, const bool is_dirty=true) + { + if (is_dirty) + { + initialize(); + } + + const Real upto(t() + duration); + + std::vector >::iterator + offset(std::partition( + observers.begin(), observers.end(), observer_every())); + + for (std::vector >::iterator i(observers.begin()); + i != observers.end(); ++i) + { + // (*i)->initialize(world_.get()); + (*i)->initialize(world_, model_); + } + + EventScheduler scheduler; + // for (std::vector >::const_iterator + // i(offset); i != observers.end(); ++i) + for (std::vector >::const_iterator + i(observers.begin()); i != observers.end(); ++i) + { + scheduler.add(std::shared_ptr( + new ObserverEvent(this, (*i).get(), t()))); + } + + while (true) + { + bool running = true; + while (next_time() < std::min(scheduler.next_time(), upto)) + { + step(); + + if (!fire_observers(observers.begin(), offset)) + { + running = false; + break; + } + } + + if (!running) + { + break; + } + else if (upto >= scheduler.next_time()) + { + step(scheduler.next_time()); + if (!fire_observers(observers.begin(), offset)) + { + running = false; + } + EventScheduler::value_type top(scheduler.pop()); + top.second->fire(); + running = ( + running && static_cast(top.second.get())->running()); + scheduler.add(top.second); + if (!running) + { + break; + } + } + else + { + step(upto); + fire_observers(observers.begin(), offset); + break; + } + } + + for (std::vector >::iterator i(observers.begin()); + i != observers.end(); ++i) + { + // (*i)->finalize(world_.get()); + (*i)->finalize(world_); + } + } + +protected: + + std::shared_ptr world_; + std::shared_ptr model_; + Integer num_steps_; +}; + +} + +#endif /* ECELL4_SIMULATOR_BASE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/NetworkModel.hpp",".hpp","3528","132","#ifndef ECELL4_NETWORK_MODEL_HPP +#define ECELL4_NETWORK_MODEL_HPP + +#include +#include +#include +#include +#include + +#include ""types.hpp"" +#include ""Species.hpp"" +#include ""ReactionRule.hpp"" +#include ""Model.hpp"" + +#include ""Context.hpp"" + + +namespace ecell4 +{ + +class NetworkModel + : public Model +{ +public: + + typedef Model base_type; + typedef base_type::species_container_type species_container_type; + typedef base_type::reaction_rule_container_type reaction_rule_container_type; + +protected: + + typedef std::map > + first_order_reaction_rules_map_type; + typedef std::map, + std::vector > + second_order_reaction_rules_map_type; + +public: + + NetworkModel() + : base_type(), species_attributes_(), species_attributes_proceed_(), reaction_rules_(), + first_order_reaction_rules_map_(), second_order_reaction_rules_map_() + { + ; + } + + virtual ~NetworkModel() + { + ; + } + + // ModelTraits + + std::vector query_reaction_rules(const Species& sp) const; + std::vector query_reaction_rules( + const Species& sp1, const Species& sp2) const; + + Integer apply(const Species& pttrn, const Species& sp) const; + std::vector apply( + const ReactionRule& rr, + const ReactionRule::reactant_container_type& reactants) const; + + Species apply_species_attributes(const Species& sp) const; + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr, + const std::map& max_stoich) const + { + return std::shared_ptr(new NetworkModel(*this)); + } + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr) const + { + return std::shared_ptr(new NetworkModel(*this)); + } + + std::shared_ptr expand(const std::vector& sp) const + { + return std::shared_ptr(new NetworkModel(*this)); + } + + // NetworkModelTraits + + bool is_static() const final + { + return true; + } + + bool update_species_attribute(const Species& sp); + void add_species_attribute(const Species& sp, const bool proceed = false); + bool has_species_attribute(const Species& sp) const; + void remove_species_attribute(const Species& sp); + + void add_reaction_rule(const ReactionRule& rr); + void remove_reaction_rule(const ReactionRule& rr); + bool has_reaction_rule(const ReactionRule& rr) const; + + const reaction_rule_container_type& reaction_rules() const + { + return reaction_rules_; + } + + const species_container_type& species_attributes() const + { + return species_attributes_; + } + + const std::vector& species_attributes_proceed() const + { + return species_attributes_proceed_; + } + +protected: + + void remove_reaction_rule(const reaction_rule_container_type::iterator i); + +protected: + + species_container_type species_attributes_; + std::vector species_attributes_proceed_; //XXX: + reaction_rule_container_type reaction_rules_; + + first_order_reaction_rules_map_type first_order_reaction_rules_map_; + second_order_reaction_rules_map_type second_order_reaction_rules_map_; +}; + +} // ecell4 + +#endif /* ECELL4_NETWORK_MODEL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/AABBSurface.hpp",".hpp","2242","106","#ifndef ECELL4_AABB_SURFACE_HPP +#define ECELL4_AABB_SURFACE_HPP + +#include ""Shape.hpp"" +#include ""shape_operators.hpp"" + +namespace ecell4 +{ + +struct AABBSurface + : public Shape +{ + AABBSurface() + : lower_(), upper_() + { + ; + } + + AABBSurface(const Real3& lower, const Real3& upper) + : lower_(lower), upper_(upper) + { + ; + } + + AABBSurface(const AABBSurface& rhs) + : lower_(rhs.lower()), upper_(rhs.upper()) + { + ; + } + + const Real3& lower() const + { + return lower_; + } + + const Real3& upper() const + { + return upper_; + } + + const Real3 center() const + { + return multiply(upper_ + lower_, 0.5); + } + + const Real3 radius() const + { + return multiply(upper_ - lower_, 0.5); + } + + Real distance_sq(const Real3 pos) const; + Real distance(const Real3& pos) const; + + Real is_inside(const Real3& coord) const + { + if(this->_is_inside(coord)) + return -1. * this->distance(coord); + else + return this->distance(coord); + } + + bool _is_inside(const Real3& coord) const + { + return (lower_[0] <= coord[0] && coord[0] <= upper_[0]) && + (lower_[1] <= coord[1] && coord[1] <= upper_[1]) && + (lower_[2] <= coord[2] && coord[2] <= upper_[2]); + } + + Real3 draw_position(std::shared_ptr& rng) const; + bool test_AABB(const Real3& l, const Real3& u) const; + bool test_segment(const Real3& p0, const Real3& p1) const; + std::pair intersect_ray(const Real3& p, const Real3& d) const; + + bool test_ray(const Real3& p, const Real3& d) const + { + return intersect_ray(p, d).first; + } + + inline Real3 corner(const int& n) const + { + const Real3 p( + ((n & 1) ? upper_[0] : lower_[0]), + ((n & 2) ? upper_[1] : lower_[1]), + ((n & 4) ? upper_[2] : lower_[2])); + return p; + } + + dimension_kind dimension() const + { + return TWO; + } + + Surface surface() const + { + return Surface(std::shared_ptr(new AABBSurface(*this))); + } + +protected: + + Real3 lower_, upper_; +}; + +}// ecell4 + +#endif /* ECELL4_AABB_SURFACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/UnitSpecies.cpp",".cpp","4317","158","#include +#include +#include + +#include ""UnitSpecies.hpp"" + + +namespace ecell4 +{ + +void UnitSpecies::clear() +{ + name_ = """"; + sites_.clear(); +} + +void UnitSpecies::deserialize(const UnitSpecies::serial_type& serial) +{ + clear(); + if (serial == """") + { + return; + } + + using namespace std; + + regex r1( + ""^\\s*(\\w+)\\s*(\\(\\s*([\\w\\s\\^=,]*)\\))?\\s*$""); + smatch results1; + if (regex_match(serial, results1, r1)) + { + name_ = std::string(results1.str(1).c_str()); + if (results1.str(3).size() > 0) + { + regex r2( + ""\\s*(\\w+)(\\s*=\\s*(\\w+))?(\\s*\\^\\s*(\\w+))?\\s*""); + // match_results results2; + smatch results2; + std::vector sites; + boost::split( + sites, static_cast(results1.str(3)), + boost::is_any_of("","")); + bool order(false); + for (std::vector::const_iterator i(sites.begin()); + i != sites.end(); ++i) + { + if (regex_match(*i, results2, r2)) + { + if (results2.str(3).size() > 0) + { + order = true; + } + else if (order) + { + throw std::invalid_argument( + ""non-keyword arg after keyword arg ["" + + (*i) + ""]""); //XXX: + } + + add_site( + results2.str(1), results2.str(3), results2.str(5)); + } + else + { + throw std::invalid_argument( + ""a wrong site specification was given ["" + + (*i) + ""]""); //XXX: + } + } + } + } + else + { + throw std::invalid_argument( + ""a wrong serial was given to UnitSpecies ["" + serial + ""]""); //XXX: + } +} + +UnitSpecies::serial_type UnitSpecies::serial() const +{ + if (sites_.size() == 0) + { + return name_; + } + + std::vector unstated, stated; + for (container_type::const_iterator i(sites_.begin()); + i != sites_.end(); ++i) + { + const std::string& + state((*i).second.first), bond((*i).second.second); + if (state.size() > 0) + { + stated.push_back((*i).first + ""="" + + (bond.size() > 0? state + ""^"" + bond : state)); + } + else + { + unstated.push_back( + bond.size() > 0? (*i).first + ""^"" + bond : (*i).first); + } + } + return name_ + ""("" + boost::algorithm::join(unstated, "","") + + (unstated.size() > 0 && stated.size() > 0? "","" : """") + + boost::algorithm::join(stated, "","") + "")""; + + // std::stringstream unstated, stated; + // bool is_unstated_empty(true), is_stated_empty(true); + // unstated << name_ << ""(""; + // for (container_type::const_iterator i(sites_.begin()); + // i != sites_.end(); ++i) + // { + // const std::string& state((*i).second.first); + // const std::string& bond((*i).second.second); + + // if (state.size() > 0) + // { + // if (is_stated_empty) + // { + // is_stated_empty = false; + // } + // else + // { + // stated << "",""; + // } + // stated << (*i).first << ""="" << state; + // if (bond.size() > 0) + // { + // stated << ""^"" << bond; + // } + // } + // else + // { + // if (is_unstated_empty) + // { + // is_unstated_empty = false; + // } + // else + // { + // unstated << "",""; + // } + // unstated << (*i).first; + // if (bond.size() > 0) + // { + // unstated << ""^"" << bond; + // } + // } + // } + // if (!is_unstated_empty && !is_stated_empty) + // { + // unstated << "",""; + // } + // unstated << stated.str() << "")""; + // return unstated.str(); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Triangle.cpp",".cpp","10701","324","#include ""Triangle.hpp"" +#include + +namespace ecell4 +{ + +Triangle::Triangle() +{ + // do nothing +} + +Triangle::Triangle(const std::array& vertices) +{ + vertices_[0] = vertices[0]; + vertices_[1] = vertices[1]; + vertices_[2] = vertices[2]; + edges_[0] = this->vertices_[1] - this->vertices_[0]; + edges_[1] = this->vertices_[2] - this->vertices_[1]; + edges_[2] = this->vertices_[0] - this->vertices_[2]; + lengths_[0] = length(edges_[0]); + lengths_[1] = length(edges_[1]); + lengths_[2] = length(edges_[2]); + angles_[0] = calc_angle(edges_[0], edges_[2] * -1.0); + angles_[1] = calc_angle(edges_[1], edges_[0] * -1.0); + angles_[2] = calc_angle(edges_[2], edges_[1] * -1.0); + normal_ = cross_product(edges_[0], edges_[2] * (-1)); + normal_ /= length(normal_); +} + +Triangle::Triangle(const TriangleView& tv) +{ + vertices_[0] = tv.vertices(0); + vertices_[1] = tv.vertices(1); + vertices_[2] = tv.vertices(2); + edges_[0] = this->vertices_[1] - this->vertices_[0]; + edges_[1] = this->vertices_[2] - this->vertices_[1]; + edges_[2] = this->vertices_[0] - this->vertices_[2]; + lengths_[0] = length(edges_[0]); + lengths_[1] = length(edges_[1]); + lengths_[2] = length(edges_[2]); + angles_[0] = calc_angle(edges_[0], edges_[2] * -1.0); + angles_[1] = calc_angle(edges_[1], edges_[0] * -1.0); + angles_[2] = calc_angle(edges_[2], edges_[1] * -1.0); + normal_ = cross_product(edges_[0], edges_[2] * (-1)); + normal_ /= length(normal_); +} + +Triangle::Triangle(const TriangleConstView& tcv) +{ + vertices_[0] = tcv.vertices(0); + vertices_[1] = tcv.vertices(1); + vertices_[2] = tcv.vertices(2); + edges_[0] = this->vertices_[1] - this->vertices_[0]; + edges_[1] = this->vertices_[2] - this->vertices_[1]; + edges_[2] = this->vertices_[0] - this->vertices_[2]; + lengths_[0] = length(edges_[0]); + lengths_[1] = length(edges_[1]); + lengths_[2] = length(edges_[2]); + angles_[0] = calc_angle(edges_[0], edges_[2] * -1.0); + angles_[1] = calc_angle(edges_[1], edges_[0] * -1.0); + angles_[2] = calc_angle(edges_[2], edges_[1] * -1.0); + normal_ = cross_product(edges_[0], edges_[2] * (-1)); + normal_ /= length(normal_); +} + +Triangle::Triangle(const Real3& a, const Real3& b, const Real3& c) +{ + vertices_[0] = a; + vertices_[1] = b; + vertices_[2] = c; + edges_[0] = vertices_[1] - vertices_[0]; + edges_[1] = vertices_[2] - vertices_[1]; + edges_[2] = vertices_[0] - vertices_[2]; + lengths_[0] = length(edges_[0]); + lengths_[1] = length(edges_[1]); + lengths_[2] = length(edges_[2]); + angles_[0] = calc_angle(edges_[0], edges_[2] * -1.0); + angles_[1] = calc_angle(edges_[1], edges_[0] * -1.0); + angles_[2] = calc_angle(edges_[2], edges_[1] * -1.0); + normal_ = cross_product(edges_[0], edges_[2] * (-1)); + normal_ /= length(normal_); +} + +Triangle& Triangle::operator=(const Triangle& rhs) +{ + vertices_ = rhs.vertices_; + edges_ = rhs.edges_; + lengths_ = rhs.lengths_; + angles_ = rhs.angles_; + normal_ = rhs.normal_; + return *this; +} + +Triangle& Triangle::operator=(const TriangleView& tv) +{ + vertices_[0] = tv.vertices(0); + vertices_[1] = tv.vertices(1); + vertices_[2] = tv.vertices(2); + edges_[0] = this->vertices_[1] - this->vertices_[0]; + edges_[1] = this->vertices_[2] - this->vertices_[1]; + edges_[2] = this->vertices_[0] - this->vertices_[2]; + lengths_[0] = length(edges_[0]); + lengths_[1] = length(edges_[1]); + lengths_[2] = length(edges_[2]); + angles_[0] = calc_angle(edges_[0], edges_[2] * -1.0); + angles_[1] = calc_angle(edges_[1], edges_[0] * -1.0); + angles_[2] = calc_angle(edges_[2], edges_[1] * -1.0); + normal_ = cross_product(edges_[0], edges_[2] * (-1)); + normal_ /= length(normal_); + return *this; +} + +Triangle& Triangle::operator=(const TriangleConstView& tcv) +{ + vertices_[0] = tcv.vertices(0); + vertices_[1] = tcv.vertices(1); + vertices_[2] = tcv.vertices(2); + edges_[0] = this->vertices_[1] - this->vertices_[0]; + edges_[1] = this->vertices_[2] - this->vertices_[1]; + edges_[2] = this->vertices_[0] - this->vertices_[2]; + lengths_[0] = length(edges_[0]); + lengths_[1] = length(edges_[1]); + lengths_[2] = length(edges_[2]); + angles_[0] = calc_angle(edges_[0], edges_[2] * -1.0); + angles_[1] = calc_angle(edges_[1], edges_[0] * -1.0); + angles_[2] = calc_angle(edges_[2], edges_[1] * -1.0); + normal_ = cross_product(edges_[0], edges_[2] * (-1)); + normal_ /= length(normal_); + return *this; +} + +Real3 closest_point_on_Triangle(const Real3& pos, const std::array& vertices) +{ + // this implementation is from Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.141-142 + + const Real3 a = vertices[0]; + const Real3 b = vertices[1]; + const Real3 c = vertices[2]; + + const Real3 ab = b - a; + const Real3 ac = c - a; + const Real3 ap = pos - a; + const Real d1 = dot_product(ab, ap); + const Real d2 = dot_product(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) + { + return a; + } + + const Real3 bp = pos - b; + const Real d3 = dot_product(ab, bp); + const Real d4 = dot_product(ac, bp); + if (d3 >= 0.0 && d4 <= d3) + { + return b; + } + + const Real vc = d1*d4 - d3*d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) + { + Real v = d1 / (d1 - d3); + return a + ab * v; + } + + const Real3 cp = pos - c; + const Real d5 = dot_product(ab, cp); + const Real d6 = dot_product(ac, cp); + if (d6 >= 0.0 && d5 <= d6) + { + return c; + } + + const Real vb = d5*d2 - d1*d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) + { + const Real w = d2 / (d2 - d6); + return a + ac * w; + } + + const Real va = d3*d6 - d5*d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) + { + const Real w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return b + (c - b) * w; + } + + const Real denom = 1.0 / (va + vb + vc); + const Real v = vb * denom; + const Real w = vc * denom; + return a + ab * v + ac * w; +} + +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri) +{ + return length_sq(closest_point_on_Triangle(pos, tri.vertices()) - pos); +} + +// ---------------------------------------------------------------------------- +// considering boundary condition + +Real minmaxdist_sq(const Real3& lw, const Real3& up, const Real3& p) noexcept +{ + const auto sq = [](const Real x) noexcept -> Real {return x * x;}; + + Real3 rm_sq(sq(lw[0] - p[0]), sq(lw[1] - p[1]), sq(lw[2] - p[2])); + Real3 rM_sq(sq(up[0] - p[0]), sq(up[1] - p[1]), sq(up[2] - p[2])); + + using std::swap; + if((up[0] + lw[0]) * 0.5 < p[0]) + { + swap(rm_sq[0], rM_sq[0]); + } + if((up[1] + lw[1]) * 0.5 < p[1]) + { + swap(rm_sq[1], rM_sq[1]); + } + if((up[2] + lw[2]) * 0.5 < p[2]) + { + swap(rm_sq[2], rM_sq[2]); + } + + const Real dx = rm_sq[0] + rM_sq[1] + rM_sq[2]; + const Real dy = rM_sq[0] + rm_sq[1] + rM_sq[2]; + const Real dz = rM_sq[0] + rM_sq[1] + rm_sq[2]; + return std::min(dx, std::min(dy, dz)); +} + +Real distance_sq_point_Triangle_impl(const Real3& pos, const Triangle& tri, const Boundary* b) +{ + const auto& vtxs = tri.vertices(); + + // first, calculate the AABB of triangle + constexpr Real inf = std::numeric_limits::infinity(); + Real3 lower, upper; + lower[0] = std::min(vtxs[0][0], std::min(vtxs[1][0], vtxs[2][0])); + lower[1] = std::min(vtxs[0][1], std::min(vtxs[1][1], vtxs[2][1])); + lower[2] = std::min(vtxs[0][2], std::min(vtxs[1][2], vtxs[2][2])); + upper[0] = std::max(vtxs[0][0], std::max(vtxs[1][0], vtxs[2][0])); + upper[1] = std::max(vtxs[0][1], std::max(vtxs[1][1], vtxs[2][1])); + upper[2] = std::max(vtxs[0][2], std::max(vtxs[1][2], vtxs[2][2])); + + const Real3 center = (lower + upper) * 0.5; + const Real3 width = (upper - lower) * 0.5; + const Real3 edge = b->edge_lengths(); + + assert(0.0 <= width[0] && 0.0 <= width[1] && 0.0 <= width[2]); + + // transpose `pos` according to the center of the AABB + const Real3 p1 = b->periodic_transpose(pos, center); + const Real d1 = length(closest_point_on_Triangle(p1, vtxs) - p1); + const Real D = 2 * (length(width) + d1); + + // Here, D is the diameter of sphere that represents the region in which + // point can be closer to the triangle than the original position, p1. + // It means that if a periodic image of p1 exceeds this range, we don't + // need to check the image. + if(D < edge[0] && D < edge[1] && D < edge[2]) // likely + { + // we don't need to check any of periodic images. The minimum distance + // between p1 and its periodic image is larger than the diameter of the + // mindist-bounding sphere. + return d1 * d1; // return square distance + } + + // expand the AABB of Triangle by default mindist. + // If periodic image exceeds this range along any axis, + // we don't need to check it. + lower[0] -= d1; + lower[1] -= d1; + lower[2] -= d1; + + upper[0] += d1; + upper[1] += d1; + upper[2] += d1; + + Real dist_sq = d1 * d1; + + // check all the possible transpose and find the minimum distance + for(std::int32_t i_x=-1; i_x<=1; ++i_x) + { + const Real p_x = p1[0] + i_x * edge[0]; + if(p_x < lower[0] || upper[0] < p_x) {continue;} + + for(std::int32_t i_y=-1; i_y<=1; ++i_y) + { + const Real p_y = p1[1] + i_y * edge[1]; + if(p_y < lower[1] || upper[1] < p_y) {continue;} + + for(std::int32_t i_z=-1; i_z<=1; ++i_z) + { + const Real p_z = p1[2] + i_z * edge[2]; + if(p_z < lower[2] || upper[2] < p_z) {continue;} + if(i_x == 0 && i_y == 0 && i_z == 0) {continue;} + + const Real3 p(p_x, p_y, p_z); + dist_sq = std::min(dist_sq, + length_sq(closest_point_on_Triangle(p, vtxs) - p)); + } + } + } + return dist_sq; +} + +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri, + const Boundary& b) +{ + return distance_sq_point_Triangle_impl(pos, tri, std::addressof(b)); +} + +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri, + const std::unique_ptr& b) +{ + return distance_sq_point_Triangle_impl(pos, tri, b.get()); +} +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri, + const std::shared_ptr& b) +{ + return distance_sq_point_Triangle_impl(pos, tri, b.get()); +} + +}// ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Journal.hpp",".hpp","1795","107","#ifndef ECELL4_JOURNAL_HPP +#define ECELL4_JOURNAL_HPP + +#include +#include + + +namespace ecell4 +{ + +class Journal +{ +public: + + enum level + { + L_OFF = 0, + L_DEBUG = 1, + L_INFO = 2, + L_WARNING = 3, + L_ERROR = 4, + L_FATAL = 5 + }; + +public: + + Journal(char const* name); + + ~Journal(); + + void level(enum level level); + enum level level() const; + + char const* name() const + { + return name_.c_str(); + } + + void debug(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_DEBUG, format, ap); + va_end(ap); + } + + void info(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_INFO, format, ap); + va_end(ap); + } + + void warn(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_WARNING, format, ap); + va_end(ap); + } + + void error(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_ERROR, format, ap); + va_end(ap); + } + + void fatal(char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(L_FATAL, format, ap); + va_end(ap); + } + + void log(enum level lv, char const* format, ...) + { + va_list ap; + va_start(ap, format); + logv(lv, format, ap); + va_end(ap); + } + + void logv(enum level lv, char const* format, va_list ap); + void flush(); + + static char const* stringize_error_level(enum level lv); + + // static Journal& get_journal(char const* name); + +private: + + void ensure_initialized(); + +protected: + + const std::string name_; + enum level level_; +}; + +} // ecell4 + +#endif /* ECELL4_JOURNAL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/collision.cpp",".cpp","14284","568","#include ""collision.hpp"" + +namespace ecell4 +{ + +namespace collision +{ + +Real distance_sq_point_AABB(const Real3& pos, const AABB& b) +{ + const Real3& upper(b.upper()); + const Real3& lower(b.lower()); + + Real Lsq(0.0); + const unsigned int ndim(3); + for (unsigned int i(0); i < ndim; ++i) + { + const Real& v(pos[i]); + if (v < lower[i]) + { + Lsq += pow_2(lower[i] - v); + } + else if (v > upper[i]) + { + Lsq += pow_2(v - upper[i]); + } + } + return Lsq; +} + +Real farthest_distance_sq_point_AABB(const Real3& pos, const AABB& b) +{ + const Real3 c(b.center()); + const Real3& lower(b.lower()); + const Real3& upper(b.upper()); + + const Real3 q( + pos[0] > c[0] ? lower[0] : upper[0], + pos[1] > c[1] ? lower[1] : upper[1], + pos[2] > c[2] ? lower[2] : upper[2]); + return length_sq(q - pos); +} + +Real distance_point_cylinder(const Real3& pos, const Cylinder& c) +{ + /* First compute the (z,r) components of pos in a coordinate system + * defined by the vectors unitR and unit_z, where unitR is + * choosen such that unitR and unit_z define a plane in which + * pos lies. */ + const Real& half_height(c.half_height()); + const Real& radius(c.radius()); + const std::pair r_z(c.to_internal(pos)); + + /* Then compute distance to cylinder. */ + const Real dz(std::fabs(r_z.second) - half_height); + const Real dr(r_z.first - radius); + + if (dz > 0) + { + // pos is (either) to the right or to the left of the cylinder. + if (r_z.first > radius) + { + // Compute distance to edge. + return std::sqrt(dz * dz + dr * dr); + } + else + { + return dz; + } + } + + if (dr > 0) + // if (dr > radius) + { + // pos is somewhere 'parallel' to the cylinder. + return dr; + } + + // Inside cylinder. + return std::max(dr, dz); +} + +Real distance_point_capsule(const Real3& pos, const Rod& r) +{ + const Real& half_length(r.half_length()); + const Real& radius(r.radius()); + const Real3 vec(pos - r.origin()); + + if (vec[0] > half_length) + { + return length(vec - Real3(half_length, 0, 0)) - radius; + } + else if (vec[0] < -half_length) + { + return length(vec + Real3(half_length, 0, 0)) - radius; + } + return length(vec - Real3(vec[0], 0, 0)) - radius; +} + +Real closest_point_segment_segment( + const Real3& p1, const Real3& q1, + const Real3& p2, const Real3& q2, + Real& s, Real& t, Real3& c1, Real3& c2) +{ + constexpr double epsilon = std::numeric_limits::epsilon(); + const Real3 d1(q1 - p1); + const Real3 d2(q2 - p2); + const Real3 r(p1 - p2); + Real a(length_sq(d1)); + Real e(length_sq(d2)); + Real f(dot_product(d2, r)); + + if (a <= epsilon && e <= epsilon) + { + c1 = p1; + c2 = p2; + return length_sq(c1 - c2); + } + + if (a <= epsilon) + { + s = 0.0; + t = f / e; + t = clamp(t, 0.0, 1.0); + } + else + { + Real c = dot_product(d1, r); + if (e <= epsilon) + { + t = 0.0; + s = clamp(-c / a, 0.0, 1.0); + } + else + { + Real b = dot_product(d1, d2); + Real denom = a * e - b * b; + if (denom != 0.0) + { + s = clamp((b * f - c * e)/ denom, 0.0, 1.0); + } + else + { + s = 0.0; + } + + t = (b * s + f) / e; + if (t < 0.0) + { + t = 0.0; + s = clamp(-c / a, 0.0, 1.0); + } + else if (t > 1.0) + { + t = 1.0; + s = clamp((b - c) / a, 0.0, 1.0); + } + } + } + + c1 = p1 + d1 * s; + c2 = p2 + d2 * t; + return length_sq(c1 - c2); +} + +bool test_AABB_AABB( + const Real3& l1, const Real3& u1, + const Real3& l2, const Real3& u2) +{ + if (u1[0] < l2[0] || l1[0] > u2[0]) + { + return false; + } + else if (u1[1] < l2[1] || l1[1] > u2[1]) + { + return false; + } + else if (u1[2] < l2[2] || l1[2] > u2[2]) + { + return false; + } + return true; +} + +bool test_segment_AABB( + const Real3& p0, const Real3& p1, const Real3& lower, const Real3& upper) +{ + constexpr double epsilon = std::numeric_limits::epsilon(); + const Real3 c((upper + lower) * 0.5); + const Real3 e(upper - c); + Real3 m(multiply(p1 - p0, 0.5)); + const Real3 d(p1 - m); + m = m - c; + + Real adx(abs(d[0])); + if (abs(m[0]) > e[0] + adx) + { + return false; + } + Real ady(abs(d[1])); + if (abs(m[1]) > e[1] + ady) + { + return false; + } + Real adz(abs(d[2])); + if (abs(m[2]) > e[2] + adz) + { + return false; + } + + adx += epsilon; + ady += epsilon; + adz += epsilon; + if (abs(m[1] * d[2] - m[2] * d[1]) > e[1] * adz + e[2] * ady) + { + return false; + } + if (abs(m[2] * d[0] - m[0] * d[2]) > e[0] * adz + e[2] * adx) + { + return false; + } + if (abs(m[0] * d[1] - m[1] * d[0]) > e[0] * ady + e[1] * adx) + { + return false; + } + return true; +} + +bool test_AABB_plane(const AABB& b, const PlanarSurface& p) +{ + const Real3 c(b.center()); + const Real3 e(b.radius()); + + const Real3& n(p.normal()); + const Real d(dot_product(p.origin(), n)); + + const Real r(e[0] * abs(n[0]) + e[1] * abs(n[1]) + e[2] * abs(n[2])); + const Real s(dot_product(n, c) - d); + return (abs(s) <= r); +} + +bool test_sphere_AABB(const Sphere& s, const AABB& b) +{ + const Real3& center(s.center()); + const Real& r(s.radius()); + + const Real Lsq(distance_sq_point_AABB(center, b)); + return (Lsq <= r * r); +} + +bool test_shell_AABB(const SphericalSurface& s, const AABB& b) +{ + const Real r(s.radius()); + const Real rsq(r * r); + const Real3& center(s.center()); + + if (distance_sq_point_AABB(center, b) > rsq) + { + return false; + } + else if (farthest_distance_sq_point_AABB(center, b) < rsq) + { + return false; + } + return true; +} + +/** + * intersect_ray_AABB + * See RTCD p.180; + */ +bool intersect_ray_AABB( + const Real3& p, const Real3& d, const Real3& lower, const Real3& upper, + Real& tmin, Real3& q) +{ + constexpr double epsilon = std::numeric_limits::epsilon(); + tmin = 0.0; + Real tmax(std::numeric_limits::infinity()); + const unsigned int ndim(3); + for (unsigned int i(0); i < ndim; ++i) + { + if (abs(d[i]) < epsilon) + { + if (p[i] < lower[i] || p[i] > upper[i]) + { + return false; + } + } + else + { + Real ood = 1.0 / d[i]; + Real t1 = (lower[i] - p[i]) * ood; + Real t2 = (upper[i] - p[i]) * ood; + if (t1 > t2) + { + const Real tmp(t1); + t1 = t2; + t2 = tmp; + } + tmin = std::max(tmin, t1); + tmax = std::min(tmax, t2); + if (tmin > tmax) + { + return false; + } + } + } + + q = p + d * tmin; + return true; +} + +bool intersect_segment_capsule( + const Real3& p1, const Real3& q1, + const Real3& p2, const Real3& q2, + const Real& radius, Real& s) +{ + Real t; + Real3 c1, c2; + const Real Lsq(closest_point_segment_segment(p1, q1, p2, q2, s, t, c1, c2)); + return Lsq <= radius * radius; +} + +bool intersect_moving_sphere_AABB( + const Sphere& s, const Real3& d, const AABB& b, Real& t) +{ + const Real3 p0(s.center()); + const Real3 p1(p0 + d); + const Real& radius(s.radius()); + const Real3& lower(b.lower()); + const Real3& upper(b.upper()); + + const AABB e( + Real3(lower[0] - radius, lower[1] - radius, lower[2] - radius), + Real3(upper[0] + radius, upper[1] + radius, upper[2] + radius)); + + Real3 p; + if (!intersect_ray_AABB(p0, d, e, t, p) || t > 1.0) + { + return false; + } + + int u(0), v(0); + if (p[0] < lower[0]) u |= 1; + if (p[0] > upper[0]) v |= 1; + if (p[1] < lower[1]) u |= 2; + if (p[1] > upper[1]) v |= 2; + if (p[2] < lower[2]) u |= 4; + if (p[2] > upper[2]) v |= 4; + const int m(u + v); + + if (m == 7) + { + Real tmin(std::numeric_limits::infinity()); + if (intersect_segment_capsule( + p0, p1, b.corner(v), b.corner(v^1), radius, t)) + { + tmin = std::min(t, tmin); + } + if (intersect_segment_capsule( + p0, p1, b.corner(v), b.corner(v^2), radius, t)) + { + tmin = std::min(t, tmin); + } + if (intersect_segment_capsule( + p0, p1, b.corner(v), b.corner(v^4), radius, t)) + { + tmin = std::min(t, tmin); + } + + if (tmin == std::numeric_limits::infinity()) + { + return false; + } + t = tmin; + return true; + } + + if ((m & (m - 1)) == 0) + { + return true; + } + + return intersect_segment_capsule( + p0, p1, b.corner(u^7), b.corner(v), radius, t); +} + +Real3 closest_point_point_triangle(const Real3& p, const Triangle& t) +{ + // this implementation is based on + // ""Real-Time Collision Detection"" by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.141-142 + + const Real3 a = t.vertices()[0]; + const Real3 b = t.vertices()[1]; + const Real3 c = t.vertices()[2]; + + const Real3 ab = b - a; + const Real3 ac = c - a; + const Real3 ap = p - a; + const Real d1 = dot_product(ab, ap); + const Real d2 = dot_product(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) + return a; + + const Real3 bp = p - b; + const Real d3 = dot_product(ab, bp); + const Real d4 = dot_product(ac, bp); + if (d3 >= 0.0 && d4 <= d3) + return b; + + const Real vc = d1*d4 - d3*d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) + { + const Real v = d1 / (d1 - d3); + return a + ab * v; + } + + const Real3 cp = p - c; + const Real d5 = dot_product(ab, cp); + const Real d6 = dot_product(ac, cp); + if (d6 >= 0.0 && d5 <= d6) + return c; + + const Real vb = d5*d2 - d1*d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) + { + const Real w = d2 / (d2 - d6); + return a + ac * w; + } + + const Real va = d3*d6 - d5*d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) + { + const Real w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return b + (c - b) * w; + } + + const Real denom = 1.0 / (va + vb + vc); + const Real v = vb * denom; + const Real w = vc * denom; + return a + ab * v + ac * w; + +} + +Real3 closest_point_point_circle(const Real3& p, const Circle& c) +{ + const Real dotp = dot_product((c.center() - p), c.normal()); + const Real3 projected(p + c.normal() * dotp); + const Real dist_on_plane2 = length_sq(projected - c.center()); + const Real rad2 = c.radius() * c.radius(); + + if(dist_on_plane2 < rad2) + return projected; + + const Real dr = std::sqrt(dist_on_plane2 / rad2); + return c.center() * (1. - dr) + projected * dr; +} + +Real3 closest_point_point_cone(const Real3&, const Cone&) +{ + throw NotImplemented(""closest_point_point_cone""); +} + +bool intersect_segment_triangle(const Real3& p, const Real3& q, + const Triangle& tri, ecell4::Barycentric& b, Real& s) +{ + // this implementation is from Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.190-194 + + const Real3 line = p - q; + const Real3 ab = tri.edges()[0]; + const Real3 ac = tri.edges()[2] * (-1.); + const Real3 normal = tri.normal(); + const Real3 v0 = tri.vertices()[0]; + + const Real d = dot_product(line, normal); + if(d < 0.0) return false; + + const Real3 ap = p - v0; + const Real t = dot_product(ap, normal); + if(t < 0.0 || d < t) return false; + + const Real3 e = cross_product(line, ap); + b[1] = dot_product(ac, e); + if(b[1] < 0. || d < b[1]) return false; + b[2] = -1.0 * dot_product(ab, e); + if(b[2] < 0. || d < b[1] + b[2]) return false; + + const Real vn = dot_product(v0, normal); + const Real distp = std::abs(dot_product(p, normal) - vn); + const Real distq = std::abs(dot_product(q, normal) - vn); + s = distp / (distp + distq); + + const Real ood = 1. / d; + b[1] *= ood; + b[2] *= ood; + b[0] = 1. - b[1] - b[2]; + return true; +} + +bool intersect_segment_circle(const Real3& pos, const Real3& disp, + const Circle& c, Real& s) +{ + throw NotImplemented(""intersect_segment_circle""); +} + +bool intersect_segment_cone(const Real3& pos, const Real3& disp, + const Cone& c, Real& s) +{ + throw NotImplemented(""intersect_segment_cone""); +} +bool intersect_ray_triangle(const Real3& position, const Real3& direction, + const Triangle& tri, ecell4::Barycentric& b, Real3& q) +{ + // this implementation is based on + // ""Real-Time Collision Detection"" by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc. + // pp.190-194 + + const Real3 ab = tri.edges()[0]; + const Real3 ac = tri.edges()[2] * (-1.); + const Real3 normal = tri.normal(); + + const Real d = dot_product(direction, normal); + if(d < 0.0) return false; + + const Real3 ap = position - tri.vertices()[0]; + const Real t = dot_product(ap, normal); + if(t < 0.0 || d < t) return false; + + const Real3 e = cross_product(direction, ap); + b[1] = dot_product(ac, e); + if(b[1] < 0. || d < b[1]) return false; + b[2] = -1.0 * dot_product(ab, e); + if(b[2] < 0. || d < b[1] + b[2]) return false; + + const Real ood = 1. / d; + b[1] *= ood; + b[2] *= ood; + b[0] = 1. - b[1] - b[2]; + q = to_absolute(b, tri); + + return true; +} + +bool intersect_ray_circle(const Real3& pos, const Real3& disp, + const Circle& c, Real& t, Real3& q) +{ + throw NotImplemented(""intersect_ray_circle""); +} + +bool intersect_ray_cone(const Real3& pos, const Real3& disp, + const Cone& c, Real& t, Real3& q) +{ + throw NotImplemented(""intersect_ray_cone""); +} + + + + + +} // collision + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/type_name_of.hpp",".hpp","458","29","#ifndef ECELL4_TYPE_NAME_OF +#define ECELL4_TYPE_NAME_OF +#include +#include + +namespace ecell4 +{ + +namespace utils +{ + +template +struct type_name_of +{ + std::string operator()() const + { + return boost::typeindex::type_id().pretty_name(); + } + + static std::string value() + { + return boost::typeindex::type_id().pretty_name(); + } +}; + +} // utils +} // ecell4 +#endif// ECELL4_TYPE_NAME_OF +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Rod.cpp",".cpp","5129","225","#include ""Rod.hpp"" +#include ""AABB.hpp"" +#include ""exceptions.hpp"" +#include ""collision.hpp"" + + +namespace ecell4 +{ + +Rod::Rod() + : length_(0.5e-6), radius_(2.0e-6), origin_() +{ + ; +} + +Rod::Rod(const Real& length, const Real& radius) + : length_(length), radius_(radius), origin_() +{ + //assert(length_ > 0); + //assert(radius_ > 0) +} + +Rod::Rod(const Real& length, const Real& radius, const Real3& origin) + : length_(length), radius_(radius), origin_(origin) +{ + ; +} + +Rod::Rod(const Rod& rhs) + : length_(rhs.length_), radius_(rhs.radius_), origin_(rhs.origin_) +{ + ; +} + +const Real& Rod::lengthX() const +{ + return length_; +} + +const Real& Rod::radius() const +{ + return radius_; +} + +const Real3& Rod::origin() const +{ + return origin_; +} + +void Rod::shift(const Real3& vec) +{ + origin_ += vec; +} + +Real Rod::is_inside(const Real3& pos) const +{ + // if (pos[0] < origin_[0] - length_ * 0.5) + // { + // const Real3 edge(origin_[0] - length_ * 0.5, origin_[1], origin_[2]); + // return ecell4::length(pos - edge) - radius_; + // } + // else if (pos[0] > origin_[0] + length_ * 0.5) + // { + // const Real3 edge(origin_[0] + length_ * 0.5, origin_[1], origin_[2]); + // return ecell4::length(pos - edge) - radius_; + // } + // else + // { + // return sqrt(pow_2(pos[1] - origin_[1]) + pow_2(pos[2] - origin_[2])) - radius_; + // } + return distance(pos); +} + +Real Rod::distance(const Real3& pos) const +{ + return collision::distance_point_capsule(pos, *this); +} + +Real3 Rod::draw_position(std::shared_ptr& rng) const +{ + // The Cylinder Part + if (rng->uniform(-4*radius_, 3*length_) >= 0) + { + const Real x(rng->uniform(-length_/2, length_/2)); + const Real theta(rng->uniform(0, M_PI*2)); + const Real r(sqrt(rng->uniform(0, pow(radius_, 2.0)))); + return origin_ + Real3(x, r*cos(theta), r*sin(theta)); + } + + // The Terminal Part + const Real theta(rng->uniform(0, M_PI)); + const Real phi(rng->uniform(0, M_PI)); + const Real r(pow(rng->uniform(0, pow(radius_, 3.0)), 1.0/3.0)); + const Real l(r*sin(phi)); + + const Integer sign(2*Integer(rng->uniform(0,2))-1); + return origin_ + Real3(sign*(length_/2+l*sin(theta)), l*cos(theta), r*cos(phi)); +} + +RodSurface Rod::surface() const +{ + return RodSurface(length_, radius_, origin_); +} + +bool Rod::test_AABB(const Real3& lower, const Real3& upper) const +{ + const Real3 axis(1.0, 0.0, 0.0); //XXX: DEFAULT + const Real3 d(axis * length_); + const Real3 p0(origin_ - axis * (length_ * 0.5)); + + Real t; + return collision::intersect_moving_sphere_AABB( + Sphere(p0, radius_), d, AABB(lower, upper), t); +} + +RodSurface::RodSurface() + : length_(0.5e-6), radius_(2.0e-6), origin_() +{ + ; +} + +RodSurface::RodSurface(const Real& length, const Real& radius) + : length_(length), radius_(radius), origin_() +{ + //assert(length_ > 0); + //assert(radius_ > 0) +} + +RodSurface::RodSurface(const Real& length, const Real& radius, const Real3& origin) + : length_(length), radius_(radius), origin_(origin) +{ + ; +} + +RodSurface::RodSurface(const RodSurface& rhs) + : length_(rhs.length_), radius_(rhs.radius_), origin_(rhs.origin_) +{ + ; +} + +const Real& RodSurface::lengthX() const +{ + return length_; +} + +const Real& RodSurface::radius() const +{ + return radius_; +} + +const Real3& RodSurface::origin() const +{ + return origin_; +} + +void RodSurface::shift(const Real3& vec) +{ + origin_ += vec; +} + +Real RodSurface::is_inside(const Real3& pos) const +{ + return distance(pos); +} + +Real RodSurface::distance(const Real3& pos) const +{ + return collision::distance_point_capsule(pos, this->inside()); +} + +Real3 RodSurface::draw_position(std::shared_ptr& rng) const +{ + // The Cylinder Part + if (rng->uniform(-2*radius_, length_) >= 0) + { + const Real x(rng->uniform(-length_/2, length_/2)); + const Real theta(rng->uniform(0, M_PI*2)); + return origin_ + Real3(x, radius_*sin(theta), radius_*cos(theta)); + } + + // The Terminal Part + const Real theta(rng->uniform(0, M_PI)); + const Real phi(rng->uniform(0, M_PI)); + const Real l(radius_*sin(phi)); + + const Integer sign(2*Integer(rng->uniform(0,2))-1); + return origin_ + Real3(sign*(length_/2+l*sin(theta)), l*cos(theta), radius_*cos(phi)); +} + +Rod RodSurface::inside() const +{ + return Rod(length_, radius_, origin_); +} + +bool RodSurface::test_AABB(const Real3& lower, const Real3& upper) const +{ + // throw NotImplemented(""not implemented yet.""); + + const Real3 axis(1.0, 0.0, 0.0); //XXX: DEFAULT + const Real3 d(axis * length_); + const Real3 p0(origin_ - axis * (length_ * 0.5)); + + Real t; + const AABB b(lower, upper); + const bool collide = collision::intersect_moving_sphere_AABB( + Sphere(p0, radius_), d, b, t); + if (collide) + { + for (int i(0); i < 8; ++i) + { + if (is_inside(b.corner(i)) > 0) + { + return true; + } + } + return false; + } + else + { + return false; + } +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/observers.cpp",".cpp","17241","683","#include ""observers.hpp"" + + +namespace ecell4 +{ + +const Real Observer::next_time() const +{ + return std::numeric_limits::infinity(); +} + +void Observer::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + ; +} + +void Observer::finalize(const std::shared_ptr& world) +{ + ; +} + +void Observer::reset() +{ + num_steps_ = 0; +} + +bool Observer::fire(const Simulator* sim, const std::shared_ptr& world) +{ + ++num_steps_; + return true; +} + +const Integer Observer::num_steps() const +{ + return num_steps_; +} + +void Observer::set_num_steps(const Integer nsteps) +{ + num_steps_ = nsteps; +} + +const Real FixedIntervalObserver::next_time() const +{ + return t0_ + dt_ * count_; +} + +const Real FixedIntervalObserver::dt() const +{ + return dt_; +} + +const Real FixedIntervalObserver::t0() const +{ + return t0_; +} + +const Integer FixedIntervalObserver::count() const +{ + return count_; +} + +void FixedIntervalObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + + if (dt_ <= 0.0) + { + throw std::invalid_argument( + ""A step interval of FixedIntervalObserver must be positive.""); + } + + if (count_ == 0) + { + t0_ = world->t(); + } + else + { + while (next_time() < world->t()) + { + ++count_; + } + } +} + +bool FixedIntervalObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + ++count_; + return base_type::fire(sim, world); +} + +void FixedIntervalObserver::reset() +{ + base_type::reset(); + count_ = 0; + t0_ = 0.0; //DUMMY +} + +void NumberLogger::log(const std::shared_ptr& world) +{ + data_container_type::value_type tmp; + tmp.push_back(world->t()); + for (species_container_type::const_iterator i(targets.begin()); + i != targets.end(); ++i) + { + tmp.push_back(world->get_value(*i)); + // tmp.push_back(world->num_molecules(*i)); + } + data.push_back(tmp); +} + +void NumberLogger::save(const std::string& filename) const +{ + if (!is_directory(filename)) + { + throw NotFound(""The output path does not exists.""); + } + + std::ofstream ofs(filename.c_str(), std::ios::out); + ofs << std::setprecision(17); + + for (species_container_type::const_iterator i(targets.begin()); + i != targets.end(); ++i) + { + ofs << "",\"""" << (*i).serial() << ""\""""; + } + ofs << std::endl; + + for (data_container_type::const_iterator i(data.begin()); + i != data.end(); ++i) + { + std::vector::const_iterator j((*i).begin()); + ofs << (*j); + ++j; + + for (; j != (*i).end(); ++j) + { + ofs << "","" << (*j); + } + ofs << std::endl; + } + + ofs.close(); +} + +void reserve_species_list( + NumberLogger& logger, const std::shared_ptr& world, const std::shared_ptr& model) +{ + if (!logger.all_species) + return; + + const std::vector species_list = world->list_species(); + std::shared_ptr expanded(model->is_static() ? model : model->expand(species_list)); + std::vector targets(expanded->list_species()); + std::copy(species_list.begin(), species_list.end(), std::back_inserter(targets)); + std::sort(targets.begin(), targets.end()); + targets.erase(std::unique(targets.begin(), targets.end()), targets.end()); + + std::size_t inc = 0; + for (std::vector::const_iterator i(targets.begin()); i != targets.end(); ++i) + { + if (std::find(logger.targets.begin(), logger.targets.end(), *i) + == logger.targets.end()) + { + logger.targets.push_back(*i); + inc++; + } + } + + if (inc > 0) + { + for (NumberLogger::data_container_type::iterator i(logger.data.begin()); + i != logger.data.end(); ++i) + { + (*i).resize(logger.targets.size() + 1, 0.0); + } + } +} + +void FixedIntervalNumberObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + reserve_species_list(logger_, world, model); + logger_.initialize(); +} + +bool FixedIntervalNumberObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + logger_.log(world); + return base_type::fire(sim, world); +} + +void FixedIntervalNumberObserver::reset() +{ + logger_.reset(); + base_type::reset(); +} + +NumberLogger::data_container_type FixedIntervalNumberObserver::data() const +{ + return logger_.data; +} + +NumberLogger::species_container_type FixedIntervalNumberObserver::targets() const +{ + return logger_.targets; +} + +void NumberObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + reserve_species_list(logger_, world, model); + logger_.initialize(); + logger_.log(world); +} + +void NumberObserver::finalize(const std::shared_ptr& world) +{ + if (logger_.data.size() == 0 || logger_.data.back()[0] != world->t()) + { + logger_.log(world); + } + base_type::finalize(world); +} + +bool NumberObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + if (sim->check_reaction()) + { + logger_.log(world); + return base_type::fire(sim, world); + } + return true; +} + +void NumberObserver::reset() +{ + logger_.reset(); + base_type::reset(); +} + +NumberLogger::data_container_type NumberObserver::data() const +{ + return logger_.data; +} + +NumberLogger::species_container_type NumberObserver::targets() const +{ + return logger_.targets; +} + +const Real TimingObserver::next_time() const +{ + if (count_ >= static_cast(t_.size())) + { + return std::numeric_limits::infinity(); + } + return t_[count_]; +} + +void TimingObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + + while (next_time() < world->t()) + { + ++count_; + } +} + +bool TimingObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + ++count_; + return base_type::fire(sim, world); +} + +void TimingObserver::reset() +{ + base_type::reset(); + count_ = 0; +} + +void TimingNumberObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + reserve_species_list(logger_, world, model); + logger_.initialize(); +} + +bool TimingNumberObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + logger_.log(world); + return base_type::fire(sim, world); +} + +void TimingNumberObserver::reset() +{ + logger_.reset(); + base_type::reset(); +} + +NumberLogger::data_container_type TimingNumberObserver::data() const +{ + return logger_.data; +} + +NumberLogger::species_container_type TimingNumberObserver::targets() const +{ + return logger_.targets; +} + +void FixedIntervalHDF5Observer::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); +} + +bool FixedIntervalHDF5Observer::fire(const Simulator* sim, const std::shared_ptr& world) +{ + if (!is_directory(filename())) + { + throw NotFound(""The output path does not exists.""); + } + + world->save(filename()); + + return base_type::fire(sim, world); +} + +const std::string FixedIntervalHDF5Observer::filename(const Integer idx) const +{ + boost::format fmt(prefix_); + + if (fmt.expected_args() == 0) + { + return fmt.str(); + } + else + { + return (fmt % idx).str(); + } +} + +void FixedIntervalCSVObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + logger_.initialize(); +} + +bool FixedIntervalCSVObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + log(world); + return base_type::fire(sim, world); +} + +void FixedIntervalCSVObserver::log(const std::shared_ptr& world) +{ + if (!is_directory(filename())) + { + throw NotFound(""The output path does not exists.""); + } + + std::ofstream ofs(filename().c_str(), std::ios::out); + logger_.save(ofs, world); + ofs.close(); +} + +const std::string FixedIntervalCSVObserver::filename(const Integer idx) const +{ + boost::format fmt(prefix_); + + if (fmt.expected_args() == 0) + { + return fmt.str(); + } + else + { + return (fmt % idx).str(); + } +} + +void FixedIntervalCSVObserver::reset() +{ + logger_.reset(); + base_type::reset(); +} + +void CSVObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + logger_.initialize(); + log(world); +} + +bool CSVObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + const bool retval = base_type::fire(sim, world); // Increment num_steps_ first. + log(world); + return retval; +} + +void CSVObserver::log(const std::shared_ptr& world) +{ + if (!is_directory(filename())) + { + throw NotFound(""The output path does not exists.""); + } + + std::ofstream ofs(filename().c_str(), std::ios::out); + logger_.save(ofs, world); + ofs.close(); +} + +const std::string CSVObserver::filename(const Integer idx) const +{ + boost::format fmt(prefix_); + + if (fmt.expected_args() == 0) + { + return fmt.str(); + } + else + { + return (fmt % idx).str(); + } +} + +void CSVObserver::reset() +{ + logger_.reset(); + base_type::reset(); +} + +void TimeoutObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + base_type::initialize(world, model); + duration_ = 0.0; + tstart_ = std::chrono::system_clock::now(); +} + +void TimeoutObserver::finalize(const std::shared_ptr& world) +{ + base_type::finalize(world); + acc_ += duration_; +} + +bool TimeoutObserver::fire(const Simulator* sim, const std::shared_ptr& world) +{ + const std::chrono::system_clock::time_point tnow = std::chrono::system_clock::now(); + duration_ = std::chrono::duration_cast(tnow - tstart_).count() * 1e-3; + + if (duration_ >= interval_) + { + return false; + } + return true; +} + +void TimeoutObserver::reset() +{ + base_type::reset(); + duration_ = 0.0; + acc_ = 0.0; + tstart_ = std::chrono::system_clock::now(); +} + +const Real FixedIntervalTrackingObserver::next_time() const +{ + return std::min(event_.next_time(), subevent_.next_time()); +} + +const Integer FixedIntervalTrackingObserver::num_steps() const +{ + return event_.num_steps + subevent_.num_steps; +} + +const Integer FixedIntervalTrackingObserver::count() const +{ + return event_.count; +} + +void FixedIntervalTrackingObserver::initialize(const std::shared_ptr& world, const std::shared_ptr& model) +{ + event_.initialize(world->t()); + subevent_.initialize(world->t()); + + if (pids_.size() == 0) + { + typedef std::vector > particle_id_pairs; + for (std::vector::const_iterator i(species_.begin()); + i != species_.end(); ++i) + { + const Species& sp(*i); + particle_id_pairs const particles(world->list_particles_exact(sp)); + pids_.reserve(pids_.size() + particles.size()); + for (particle_id_pairs::const_iterator j(particles.begin()); + j != particles.end(); ++j) + { + pids_.push_back((*j).first); + } + } + + prev_positions_.clear(); + prev_positions_.resize(pids_.size(), Real3(0, 0, 0)); + trajectories_.clear(); + trajectories_.resize(pids_.size(), std::vector()); + strides_.clear(); + strides_.resize(pids_.size(), Real3(0, 0, 0)); + t_.clear(); + } +} + +bool FixedIntervalTrackingObserver::fire( + const Simulator* sim, const std::shared_ptr& world) +{ + if (subevent_.next_time() <= event_.next_time()) + { + fire_subevent(sim, world); + } + else + { + fire_event(sim, world); + } + return true; +} + +void FixedIntervalTrackingObserver::fire_subevent( + const Simulator* sim, const std::shared_ptr& world) +{ + typedef std::vector > particle_id_pairs; + + const Real3& edge_lengths(world->edge_lengths()); + + std::vector::iterator j(prev_positions_.begin()); + std::vector::iterator k(strides_.begin()); + for (std::vector::iterator i(pids_.begin()); + i != pids_.end(); ++i, ++j, ++k) + { + if ((*i) == ParticleID() || world->has_particle(*i)) + { + continue; + } + + const Real3 pos((*j) - (*k)); + Real Lmin(threshold_); + ParticleID newpid; + + for (std::vector::const_iterator l(species_.begin()); + l != species_.end(); ++l) + { + const Species& sp(*l); + particle_id_pairs const particles(world->list_particles_exact(sp)); + for (particle_id_pairs::const_iterator m(particles.begin()); + m != particles.end(); ++m) + { + if (std::find(pids_.begin(), pids_.end(), (*m).first) == pids_.end()) + { + const Real L(distance(pos, (*m).second.position(), edge_lengths)); + if (L < Lmin) + { + Lmin = L; + newpid = (*m).first; + } + } + } + } + + (*i) = newpid; + } + + if (resolve_boundary_) + { + const Real3 edge_lengths(world->edge_lengths()); + std::vector::iterator j(prev_positions_.begin()); + std::vector::iterator k(strides_.begin()); + for (std::vector::const_iterator i(pids_.begin()); + i != pids_.end(); ++i, ++j, ++k) + { + if ((*i) != ParticleID() && world->has_particle(*i)) + { + Real3& stride(*k); + Real3 pos(stride + world->get_particle(*i).second.position()); + if (subevent_.num_steps > 0) + { + const Real3& prev(*j); + for (unsigned int dim(0); dim != 3; ++dim) + { + const Real L(edge_lengths[dim]); + if (pos[dim] - prev[dim] >= L * 0.5) + { + stride[dim] -= L; + pos[dim] -= L; + } + else if (pos[dim] - prev[dim] <= L * -0.5) + { + stride[dim] += L; + pos[dim] += L; + } + } + } + (*j) = pos; + } + } + } + + subevent_.fire(); +} + +void FixedIntervalTrackingObserver::fire_event( + const Simulator* sim, const std::shared_ptr& world) +{ + t_.push_back(world->t()); + + const Real3 edge_lengths(world->edge_lengths()); + std::vector::const_iterator j(prev_positions_.begin()); + std::vector::const_iterator k(strides_.begin()); + std::vector >::iterator l(trajectories_.begin()); + for (std::vector::const_iterator i(pids_.begin()); + i != pids_.end(); ++i) + { + if (world->has_particle(*i)) + { + const Real3& stride(*k); + Real3 pos(stride + world->get_particle(*i).second.position()); + + if (resolve_boundary_ && subevent_.num_steps > 0) + { + const Real3& prev(*j); + + for (unsigned int dim(0); dim != 3; ++dim) + { + const Real L(edge_lengths[dim]); + if (pos[dim] - prev[dim] >= L * 0.5) + { + pos[dim] -= L; + } + else if (pos[dim] - prev[dim] <= L * -0.5) + { + pos[dim] += L; + } + } + } + + (*l).push_back(pos); + } + ++j; + ++k; + ++l; + } + + event_.fire(); +} + +void FixedIntervalTrackingObserver::reset() +{ + event_.reset(); + subevent_.reset(); + + prev_positions_.clear(); + prev_positions_.resize(pids_.size(), Real3(0, 0, 0)); + trajectories_.clear(); + trajectories_.resize(pids_.size(), std::vector()); + strides_.clear(); + strides_.resize(pids_.size(), Real3(0, 0, 0)); + t_.clear(); +} + +const std::vector >& FixedIntervalTrackingObserver::data() const +{ + return trajectories_; +} + +const Integer FixedIntervalTrackingObserver::num_tracers() const +{ + return pids_.size(); +} + +const std::vector& FixedIntervalTrackingObserver::t() const +{ + return t_; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/LatticeSpaceCellListImpl.hpp",".hpp","11334","384","#ifndef ECELL4_LATTICE_SPACE_CELL_LIST_IMPL_HPP +#define ECELL4_LATTICE_SPACE_CELL_LIST_IMPL_HPP + +#include ""Context.hpp"" +#include ""MoleculePool.hpp"" +#include ""VacantType.hpp"" +// #include +#include + +#include ""HCPLatticeSpace.hpp"" +#include ""comparators.hpp"" + +namespace ecell4 +{ + +inline unsigned int ceilint(const unsigned int x, const unsigned int y) +{ + return x / y + (x % y != 0); +} + +class LatticeSpaceCellListImpl : public HCPLatticeSpace +{ +public: + typedef HCPLatticeSpace base_type; + + typedef base_type::coordinate_id_pair_type coordinate_id_pair_type; + typedef base_type::coordinate_type coordinate_type; + + typedef std::vector< + std::pair, coordinate_type>> + cell_type; + typedef std::vector matrix_type; + typedef std::map> + structure_container_type; + +protected: + typedef std::unordered_map> + voxel_pool_map_type; + typedef std::unordered_map> + molecule_pool_map_type; + // typedef std::map< + // Species, std::shared_ptr > voxel_pool_map_type; + // typedef std::map< + // Species, std::shared_ptr > molecule_pool_map_type; + +public: + LatticeSpaceCellListImpl(const Real3 &edge_lengths, + const Real &voxel_radius, + const Integer3 &matrix_sizes, + const bool is_periodic = true) + : base_type(edge_lengths, voxel_radius, is_periodic), + is_periodic_(is_periodic), matrix_sizes_(matrix_sizes), + matrix_(matrix_sizes_[0] * matrix_sizes_[1] * matrix_sizes_[2]) + { + cell_sizes_[0] = ceilint(col_size_, matrix_sizes_[0]); + cell_sizes_[1] = ceilint(row_size_, matrix_sizes_[1]); + cell_sizes_[2] = ceilint(layer_size_, matrix_sizes_[2]); + + for (coordinate_type coord(0); coord < actual_size(); ++coord) + { + vacant_->add_voxel(coordinate_id_pair_type(ParticleID(), coord)); + } + + border_ = std::shared_ptr( + new MoleculePool(Species(""Border"", voxel_radius_, 0), vacant_)); + periodic_ = std::shared_ptr( + new MoleculePool(Species(""Periodic"", voxel_radius_, 0), vacant_)); + } + + virtual ~LatticeSpaceCellListImpl() {} + + /** + */ + + inline matrix_type::size_type + coordinate2index(const coordinate_type &coord) const + { + return global2index(coordinate2global(coord)); + } + + inline matrix_type::size_type global2index(const Integer3 &g) const + { + return (g.col / cell_sizes_[0]) + + matrix_sizes_[0] * + ((g.row / cell_sizes_[1]) + + matrix_sizes_[1] * (g.layer / cell_sizes_[2])); + } + + cell_type::iterator find_from_cell(const coordinate_type &coord, + cell_type &cell) + { + return std::find_if( + cell.begin(), cell.end(), + utils::pair_second_element_unary_predicator< + std::shared_ptr, coordinate_type>(coord)); + // cell_type::iterator i(cell.begin()); + // for (; i != cell.end(); ++i) + // { + // if ((*i).second == coord) + // { + // return i; + // } + // } + // return i; + } + + cell_type::const_iterator find_from_cell(const coordinate_type &coord, + const cell_type &cell) const + { + return std::find_if( + cell.begin(), cell.end(), + utils::pair_second_element_unary_predicator< + std::shared_ptr, coordinate_type>(coord)); + // cell_type::const_iterator i(cell.begin()); + // for (; i != cell.end(); ++i) + // { + // if ((*i).second == coord) + // { + // return i; + // } + // } + // return i; + } + + void update_matrix(const coordinate_type &coord, + std::shared_ptr vp) + { + cell_type &cell(matrix_[coordinate2index(coord)]); + cell_type::iterator i(find_from_cell(coord, cell)); + + if (i != cell.end()) + { + if (vp->is_vacant()) + { + cell.erase(i); + } + else + { + (*i).first = vp; + } + } + else if (!vp->is_vacant()) + { + cell.push_back(std::make_pair(vp, coord)); + } + else + { + throw NotFound(""1""); + } + } + + void update_matrix(const coordinate_type &from_coord, + const coordinate_type &to_coord, + std::shared_ptr vp) + { + const matrix_type::size_type from_idx(coordinate2index(from_coord)), + to_idx(coordinate2index(to_coord)); + if (from_idx == to_idx) + { + cell_type &cell(matrix_[from_idx]); + cell_type::iterator i(find_from_cell(from_coord, cell)); + if (i == cell.end()) + { + throw NotFound(""2""); + } + (*i).first = vp; + (*i).second = to_coord; + } + else + { + cell_type &cell(matrix_[from_idx]); + cell_type::iterator i(find_from_cell(from_coord, cell)); + if (i == cell.end()) + { + throw NotFound(""3""); + } + cell.erase(i); + matrix_[to_idx].push_back(std::make_pair(vp, to_coord)); + } + } + + void dump_matrix() + { + std::cout << ""====================="" << std::endl; + for (matrix_type::size_type i(0); i != matrix_.size(); ++i) + { + cell_type &c(matrix_[i]); + if (c.size() == 0) + { + continue; + } + + std::cout << i << "" : ""; + for (cell_type::const_iterator j(c.begin()); j != c.end(); ++j) + { + std::cout << (*j).second << "" ""; + } + std::cout << std::endl; + } + std::cout << ""====================="" << std::endl; + } + + virtual bool update_voxel(const ParticleID &pid, const Species &species, + const coordinate_type coordinate); + virtual bool add_voxel(const Species &sp, const ParticleID &pid, + const coordinate_type &coord); + + virtual bool remove_voxel(const ParticleID &pid) + { + std::pair, coordinate_type> target( + __get_coordinate(pid)); + if (target.second != -1) + { + std::shared_ptr vp(target.first); + const coordinate_type coord(target.second); + if (!vp->remove_voxel_if_exists(coord)) + { + return false; + } + + vp->location()->add_voxel( + coordinate_id_pair_type(ParticleID(), coord)); + update_matrix(coord, vp->location()); + return true; + } + return false; + } + + virtual bool remove_voxel(const coordinate_type &coord) + { + std::shared_ptr vp(get_voxel_pool_at(coord)); + if (vp->is_vacant()) + { + return false; + } + + if (vp->remove_voxel_if_exists(coord)) + { + // ??? + update_matrix(coord, vacant_); + return true; + } + return true; + } + + virtual bool move(const coordinate_type &src, const coordinate_type &dest, + const std::size_t candidate = 0) + { + coordinate_type tmp_dest(dest); + if (src == tmp_dest) + { + return false; + } + + std::shared_ptr src_vp(get_voxel_pool_at(src)); + if (src_vp->is_vacant()) + { + return true; + } + + std::shared_ptr dest_vp(get_voxel_pool_at(tmp_dest)); + if (dest_vp == border_) + { + return false; + } + else if (dest_vp == periodic_) + { + tmp_dest = periodic_transpose(tmp_dest); + dest_vp = get_voxel_pool_at(tmp_dest); + } + + if (dest_vp != src_vp->location()) + { + return false; + } + + src_vp->replace_voxel(src, tmp_dest); + dest_vp->replace_voxel(tmp_dest, src); + if (!dest_vp->is_vacant()) + { + update_matrix(src, dest_vp); + update_matrix(tmp_dest, src_vp); + } + else + { + update_matrix(src, tmp_dest, src_vp); + } + return true; + } + + virtual bool can_move(const coordinate_type &src, + const coordinate_type &dest) const + { + if (src == dest) + { + return false; + } + + std::shared_ptr src_vp(get_voxel_pool_at(src)); + if (src_vp->is_vacant()) + { + return false; + } + + std::shared_ptr dest_vp(get_voxel_pool_at(dest)); + + if (dest_vp == border_) + { + return false; + } + + if (dest_vp == periodic_) + { + dest_vp = get_voxel_pool_at(periodic_transpose(dest)); + } + + return (dest_vp == src_vp->location()); + } + + std::shared_ptr + get_voxel_pool_at(const coordinate_type &coord) const; + + coordinate_type get_neighbor(const coordinate_type &coord, + const Integer &nrand) const + { + coordinate_type const dest = get_neighbor_(coord, nrand); + return (!is_periodic_ || is_inside(dest) ? dest + : periodic_transpose(dest)); + } + + virtual void add_structure(const Species &sp, + const std::shared_ptr &s, + const std::string loc); + virtual const std::shared_ptr & + get_structure(const Species &sp) const; + virtual const Shape::dimension_kind + get_structure_dimension(const Species &sp) const; + + virtual Integer num_molecules(const Species &sp) const; + + /** + */ + +#ifdef WITH_HDF5 + /* + * HDF5 Save + */ + void save_hdf5(H5::Group *root) const + { + // save_lattice_space(*this, root, ""LatticeSpaceCellListImpl""); + throw NotSupported( + ""LatticeSpaceCellListImpl::save_hdf5 is not supported yet.""); + } + + void load_hdf5(const H5::Group &root) + { + // load_lattice_space(root, this); + // load_lattice_space(root, this, ""LatticeSpaceCellListImpl""); + throw NotSupported( + ""LatticeSpaceCellListImpl::load_hdf5 is not supported yet.""); + } +#endif + +protected: + std::pair, coordinate_type> + __get_coordinate(const ParticleID &pid); + std::pair, coordinate_type> + __get_coordinate(const ParticleID &pid) const; + +protected: + bool is_periodic_; + + std::shared_ptr border_; + std::shared_ptr periodic_; + + Integer3 matrix_sizes_, cell_sizes_; + matrix_type matrix_; + structure_container_type structures_; +}; + +} // namespace ecell4 + +#endif /* ECELL4_LATTICE_SPACE_CELL_LIST_IMPL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/AABBSurface.cpp",".cpp","3986","139","#include ""AABB.hpp"" +#include ""AABBSurface.hpp"" +#include ""collision.hpp"" + + +namespace ecell4 +{ + +Real AABBSurface::distance_sq(const Real3 pos) const +{ + if(this->_is_inside(pos)) + { + const Real3 dupper = upper_ - pos; + const Real3 dlower = lower_ - pos; + const Real du = std::min(std::min(dupper[0], dupper[1]), dupper[2]); + const Real dl = std::min(std::min(dlower[0], dlower[1]), dlower[2]); + const Real dmin = std::min(du, dl); + return dmin * dmin; + } + else + { + return collision::distance_sq_point_AABB(pos, AABB(lower_, upper_)); + } +} + +Real AABBSurface::distance(const Real3& pos) const +{ + if(this->_is_inside(pos)) + { + const Real3 dupper = upper_ - pos; + const Real3 dlower = lower_ - pos; + const Real du = std::min(std::min(dupper[0], dupper[1]), dupper[2]); + const Real dl = std::min(std::min(dlower[0], dlower[1]), dlower[2]); + return std::min(du, dl); + } + else + { + return sqrt(collision::distance_sq_point_AABB(pos, AABB(lower_, upper_))); + } +} + +Real3 AABBSurface::draw_position( + std::shared_ptr& rng) const +{ + const Real Sxy = (upper_[0] - lower_[0]) * (upper_[1] - lower_[1]); + const Real Syz = (upper_[1] - lower_[1]) * (upper_[2] - lower_[2]); + const Real Szx = (upper_[1] - lower_[1]) * (upper_[0] - lower_[0]); + const Real Stot = (Sxy + Syz + Szx) * 2; + Real rnd = rng->uniform(0., Stot); + + if((rnd -= Sxy) < 0.) + { + return Real3(rng->uniform(lower_[0], upper_[0]), + rng->uniform(lower_[1], upper_[1]), + lower_[2]); + } + else if((rnd -= Sxy) < 0.) + { + return Real3(rng->uniform(lower_[0], upper_[0]), + rng->uniform(lower_[1], upper_[1]), + upper_[2]); + } + else if((rnd -= Syz) < 0.) + { + return Real3(lower_[0], + rng->uniform(lower_[1], upper_[1]), + rng->uniform(lower_[2], upper_[2])); + } + else if((rnd -= Syz) < 0.) + { + return Real3(upper_[0], + rng->uniform(lower_[1], upper_[1]), + rng->uniform(lower_[2], upper_[2])); + } + else if((rnd -= Szx) < 0.) + { + return Real3(rng->uniform(lower_[0], upper_[0]), + lower_[1], + rng->uniform(lower_[2], upper_[2])); + } + else if((rnd -= Szx) < 0.) + { + return Real3(rng->uniform(lower_[0], upper_[0]), + upper_[1], + rng->uniform(lower_[2], upper_[2])); + } + else + { + throw std::logic_error(""invalid random number""); + } +} + +bool AABBSurface::test_AABB(const Real3& l, const Real3& u) const +{// same as AABB case? + return collision::test_AABB_AABB(lower_, upper_, l, u); +} + +bool AABBSurface::test_segment(const Real3& p0, const Real3& p1) const +{ + if(this->_is_inside(p0) && this->_is_inside(p1)) + { + return false; + } + else if(this->_is_inside(p0) || this->_is_inside(p1)) + { + return true; + } + else + { + return collision::test_segment_AABB(p0, p1, lower_, upper_); + } +} + +std::pair AABBSurface::intersect_ray(const Real3& p, const Real3& d) const +{ + if(this->_is_inside(p)) + { + Real tmin = std::numeric_limits::infinity(); + for(std::size_t i=0; i<3; ++i) + { + if(std::abs(d[i]) < std::numeric_limits::epsilon()) continue; + const Real tmp = (d[i] > 0) ? (this->upper_[i] - p[i]) / d[i] : + (this->lower_[i] - p[i]) / d[i] ; + tmin = std::min(tmin, tmp); + } + bool retval(tmin <= 1.0); + return std::make_pair(retval, tmin); + } + else + { + Real tmin; + Real3 q; + const bool retval(collision::intersect_ray_AABB(p, d, lower_, upper_, tmin, q)); + return std::make_pair(retval, tmin); + } +} + +}// ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Polygon.hpp",".hpp","35083","1021","#ifndef ECELL4_HALFEDGE_POLYGON_HPP +#define ECELL4_HALFEDGE_POLYGON_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WITH_HDF5 +#include ""PolygonHDF5Writer.hpp"" +#endif + +#include + +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +struct FaceID: + public Identifier +{ + typedef Identifier base_type; + + FaceID(const value_type& value = value_type(0, 0)) + : base_type(value) + {} +}; +struct EdgeID: + public Identifier +{ + typedef Identifier base_type; + + EdgeID(const value_type& value = value_type(0, 0)) + : base_type(value) + {} +}; +struct VertexID: + public Identifier +{ + typedef Identifier base_type; + + VertexID(const value_type& value = value_type(0, 0)) + : base_type(value) + {} +}; + + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const FaceID& fid) +{ + os << ""FID("" << fid().first << ':' << fid().second << "")""; + return os; +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const EdgeID& eid) +{ + os << ""EID("" << eid().first << ':' << eid().second << "")""; + return os; +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const VertexID& vid) +{ + os << ""VID("" << vid().first << ':' << vid().second << "")""; + return os; +} + +} // ecell4 + +namespace std { + +template<> +struct hash +{ + typedef std::size_t result_type; + typedef ecell4::FaceID argument_type; + result_type operator()(const argument_type& val) const + { + return static_cast(val().first ^ val().second); + } +}; +template<> +struct hash +{ + typedef std::size_t result_type; + typedef ecell4::EdgeID argument_type; + result_type operator()(const argument_type& val) const + { + return static_cast(val().first ^ val().second); + } +}; +template<> +struct hash +{ + typedef std::size_t result_type; + typedef ecell4::VertexID argument_type; + result_type operator()(const argument_type& val) const + { + return static_cast(val().first ^ val().second); + } +}; +} // std + +namespace ecell4 +{ + +// Static Polygon. once made, the shape never change. +// (Face|Edge|Vertex)ID are just std::size_t. +// Any hole or duplicated vertex will be treated as invalid structure. +class Polygon : public Shape +{ + public: + + static const Real absolute_tolerance; + static const Real relative_tolerance; + + struct vertex_data + { + Real apex_angle; // total angle around this vertex + Real3 position; // position of this vertex + std::vector > outgoing_edges; + // these are garanteed to be sorted in the order that + // (next of next of opposite of one edge on Halfedge polygon). + }; + struct edge_data + { + Real length; // length of this edge + Real tilt; // tilt from this->face to opposite face + Real3 direction; // direction independent from boundary + VertexID target; // destination vertex + FaceID face; // belonging face + EdgeID next; // edge on the same face, starting from target + EdgeID opposite_edge; + }; + struct face_data + { + Triangle triangle; // not considering Boundary, contains just the shape + std::array< EdgeID, 3> edges; // idx consistent with triangle + std::array vertices; // idx consistent with triangle + + std::size_t index_of(const VertexID& vid) const + { + if(vertices[0] == vid){return 0;} + if(vertices[1] == vid){return 1;} + if(vertices[2] == vid){return 2;} + return 3; + } + std::size_t index_of(const EdgeID& eid) const + { + if(edges[0] == eid){return 0;} + if(edges[1] == eid){return 1;} + if(edges[2] == eid){return 2;} + return 3; + } + + std::vector neighbors; // for searching objects on it + // neighbor list; that has pairs of {Fid, unfolded Triangle}. + // each index corresponds to that of vertices. + std::array >, 3> neighbor_ccw; + std::array >, 3> neighbor_cw; + // XXX: distance calculation between points on a polygon is complicated. + // 1. there are several `local-minima` between any combination of points. + // so all the minima should be calculated and the shortest path + // should be found from them. + // 2. each `local-minima` corresponds to a straight line along the + // unfolded triangles around corresponding vertices (excluding the + // case that is described in `3`). + // * if the two faces that two positions locates on are not connected + // by one vertices, it is not able to find the shortest path w/o + // employing some costly minimization technique. + // 3. if the angle between p1-v-p2 exceeds pi, the shortest path become + // the path that goes through the vertex. + // * this means that before calculating distance, the angle should be + // calculated and checked whether it exceeds pi or not. + // 4. an apex angle around a vertex can be any value. + // * by adding a pyramid instead of one face around a vertex, the + // angle will increase. We can put the pyramid that infinitely thin. + // it enables us to put any number of pyramids around one vertex, + // increasing the apex angle between the vertex. + }; + + struct FaceAABBGetter + { + AABB operator()(const face_data& f, const Real margin) const noexcept + { + const auto& v1 = f.triangle.vertices()[0]; + const auto& v2 = f.triangle.vertices()[1]; + const auto& v3 = f.triangle.vertices()[2]; + const Real3 upper(std::max(std::max(v1[0], v2[0]), v3[0]), + std::max(std::max(v1[1], v2[1]), v3[1]), + std::max(std::max(v1[2], v2[2]), v3[2])); + const Real3 lower(std::min(std::min(v1[0], v2[0]), v3[0]), + std::min(std::min(v1[1], v2[1]), v3[1]), + std::min(std::min(v1[2], v2[2]), v3[2])); + + const auto padding = (upper - lower) * (margin * 0.5); + return AABB(lower - padding, upper + padding); + } + }; + typedef PeriodicRTree face_container_type; + + typedef ObjectIDContainer vertex_container_type; + typedef ObjectIDContainer< EdgeID, edge_data> edge_container_type; + + public: + + Polygon(const Real3& edge_lengths = Real3(1, 1, 1), + const Integer3& matrix_sizes = Integer3(3, 3, 3)) + : total_area_(0.0), edge_length_(edge_lengths), faces_(edge_lengths, 0.0) + { + const std::size_t x_size = matrix_sizes[0]; + const std::size_t y_size = matrix_sizes[1]; + + assert(x_size != 0); + assert(y_size != 0); + + const Real dx = edge_lengths[0] / x_size; + const Real dy = edge_lengths[1] / y_size; + const Real z = edge_lengths[2] / 2.0; // at the middle of Z-axis + + std::vector ts; + ts.reserve(x_size * y_size * 2); + + for(std::size_t yi = 0; yi < y_size; ++yi) + { + for(std::size_t xi = 0; xi < x_size; ++xi) + { + // 4___ 3 + // y | /| upper left = {1, 3, 4} + // ^ |/_| lower right = {1, 2, 3} + // | 1 2 + // | + // --> x + + const Real3 v1(dx * xi , dy * yi , z); + const Real3 v2(dx * (xi+1), dy * yi , z); + const Real3 v3(dx * (xi+1), dy * (yi+1), z); + const Real3 v4(dx * xi , dy * (yi+1), z); + + ts.push_back(Triangle(v1, v3, v4)); + ts.push_back(Triangle(v1, v2, v3)); + } + } + this->assign(ts); + } + Polygon(const Real3& edge_length, const std::vector& ts) + : total_area_(0.0), edge_length_(edge_length), faces_(edge_length, 0.0) + { + this->assign(ts); + } + ~Polygon(){} + + Polygon(const Polygon& rhs) + : total_area_(rhs.total_area_), edge_length_(rhs.edge_length_), + vertices_(rhs.vertices_), faces_(rhs.faces_), edges_(rhs.edges_) + {} + Polygon& operator=(const Polygon& rhs) + { + this->total_area_ = rhs.total_area_; + this->edge_length_ = rhs.edge_length_; + this->vertices_ = rhs.vertices_; + this->faces_ = rhs.faces_; + this->edges_ = rhs.edges_; + return *this; + } + + // clear current polygon and assign different one. + // tolerances are used to detect the same vertices in different triangles. + void assign(const std::vector& ts); + + // move `pos` to `pos + disp`. + std::pair + travel(const std::pair& pos, const Real3& disp) const; + std::pair + travel(const std::pair& pos, const Real3& disp, + const std::size_t restraint) const; + + // pos1 -> pos2 <=> pos2 - pos1 + Real3 direction (const std::pair& pos1, + const std::pair& pos2) const; + + Real distance_sq(const std::pair& pos1, + const std::pair& pos2) const; + Real distance (const std::pair& pos1, + const std::pair& pos2) const + { + return std::sqrt(this->distance_sq(pos1, pos2)); + } + + Real distance_sq(const std::pair& pos1, + const std::pair& pos2) const; + Real distance (const std::pair& pos1, + const std::pair& pos2) const + { + return std::sqrt(this->distance_sq(pos1, pos2)); + } + Real distance_sq(const std::pair& pos1, + const std::pair& pos2) const + { + return this->distance_sq(pos2, pos1); + } + Real distance (const std::pair& pos1, + const std::pair& pos2) const + { + return this->distance(pos2, pos1); + } + + Real distance_sq(const std::pair& pos1, + const std::pair& pos2) const; + Real distance(const std::pair& pos1, + const std::pair& pos2) const; + + // half-edge traverse + // next edge: the edge belonging the same face, + // starting from the target of current edge + EdgeID next_of(const EdgeID eid) const + {return this->edge_at(eid).next;} + + // opposite edge: the edge that starts from the target of current edge, + // ends at the starting point of current edge. + EdgeID opposite_of(const EdgeID eid) const + {return this->edge_at(eid).opposite_edge;} + + // target vertex: the vertex that current edge stops at. + VertexID target_of(const EdgeID eid) const + {return this->edge_at(eid).target;} + + // belonging face: the face that corresponds to the current edge. + FaceID face_of(const EdgeID eid) const + {return this->edge_at(eid).face;} + + // edge ids that are corresponds to the face + std::array const& edges_of(const FaceID fid) const + {return this->face_at(fid).edges;} + + // vertex ids that are corresponds to the face + std::array const& vertices_of(const FaceID fid) const + {return this->face_at(fid).vertices;} + + // edge ids that starts from the vertex + // XXX: it returns rvalue, so the iterator cannot be used + std::vector outgoing_edges(const VertexID vid) const + { + const std::vector >& + oedges = this->vertex_at(vid).outgoing_edges; + + std::vector retval(oedges.size()); + for(std::size_t i=0; i > const& + outgoing_edge_and_angles(const VertexID vid) const + { + return this->vertex_at(vid).outgoing_edges; + } + + std::vector neighbor_faces_of(const FaceID& fid) const + { + return this->face_at(fid).neighbors; + } + std::vector neighbor_faces_of(const VertexID& vid) const + { + const std::vector >& + outs = this->vertex_at(vid).outgoing_edges; + + std::vector fids; + fids.reserve(outs.size() * 2); + for(std::vector >::const_iterator + i(outs.begin()), e(outs.end()); i!=e; ++i) + { + fids.push_back(this->face_of(i->first)); + fids.push_back(this->face_of( + this->opposite_of(this->next_of(i->first)))); + } + return fids; + } + + std::vector neighbor_vertices_of(const FaceID& fid) const + { + std::vector vids; + vids.reserve(6); + + std::array const& eids = this->edges_of(fid); + for(std::size_t i=0; i<3; ++i) + { + vids.push_back(this->target_of(eids[i])); + vids.push_back(this->target_of( + this->next_of(this->opposite_of(eids[i])))); + } + return vids; + } + std::vector neighbor_vertices_of(const VertexID& vid) const + { + const std::vector >& + outs = this->vertex_at(vid).outgoing_edges; + std::vector vids; + vids.reserve(outs.size() * 2); + for(std::vector >::const_iterator + i(outs.begin()), e(outs.end()); i!=e; ++i) + { + vids.push_back(this->target_of(i->first)); + vids.push_back(this->target_of( + this->next_of(this->opposite_of(this->next_of(i->first))))); + } + return vids; + } + + // accessor --------------------------------------------------------------- + + Real apex_angle_at(const VertexID& vid) const + { + return this->vertex_at(vid).apex_angle; + } + Real3 position_at(const VertexID& vid) const + { + return this->vertex_at(vid).position; + } + std::vector connecting_faces(const VertexID& vid) const + { + std::vector retval; + const std::vector >& + outs = this->outgoing_edge_and_angles(vid); + for(typename std::vector >::const_iterator + i(outs.begin()), e(outs.end()); i!=e; ++i) + { + retval.push_back(this->face_of(i->first)); + } + return retval; + } + + Real length_of(const EdgeID& eid) const + { + return this->edge_at(eid).length; + } + Real tilt_angle_at(const EdgeID& eid) const + { + return this->edge_at(eid).tilt; + } + Real3 direction_of(const EdgeID& eid) const + { + return this->edge_at(eid).direction; + } + + Triangle const& triangle_at(const FaceID& fid) const + { + return this->face_at(fid).triangle; + } + std::vector const& neighbors(const FaceID& fid) const + { + return this->face_at(fid).neighbors; + } + + std::vector, Real>> + list_faces_within_radius(const Real3& pos, const Real& radius) const + { + return this->list_faces_within_radius_impl(pos, radius, + [](const FaceID&) noexcept -> bool { + return false; + }); + } + std::vector, Real>> + list_faces_within_radius(const Real3& pos, const Real& radius, + const FaceID& ignore1) const + { + return this->list_faces_within_radius_impl(pos, radius, + [=](const FaceID& fid) noexcept -> bool { + return fid == ignore1; + }); + } + std::vector, Real>> + list_faces_within_radius(const Real3& pos, const Real& radius, + const FaceID& ignore1, const FaceID& ignore2) const + { + return this->list_faces_within_radius_impl(pos, radius, + [=](const FaceID& fid) noexcept -> bool { + return fid == ignore1 || fid == ignore2; + }); + } + + /* inherited from shape --------------------------------------------------*/ + dimension_kind dimension() const {return THREE;} // TWO? + + Real is_inside(const Real3&) const + { + throw NotImplemented(""ecell4::Polygon::is_inside""); + } + + bool test_AABB(const Real3&, const Real3&) const + { + throw NotImplemented(""ecell4::Polygon::test_AABB""); + } + + void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + const Real maxr = std::numeric_limits::max(); + lower = Real3( maxr, maxr, maxr); + upper = Real3(-maxr, -maxr, -maxr); + + for(vertex_container_type::const_iterator + i(this->vertices_.begin()), e(this->vertices_.end()); i!=e; ++i) + { + lower[0] = std::min(lower[0], i->second.position[0]); + lower[1] = std::min(lower[1], i->second.position[1]); + lower[2] = std::min(lower[2], i->second.position[2]); + + upper[0] = std::max(upper[0], i->second.position[0]); + upper[1] = std::max(upper[1], i->second.position[1]); + upper[2] = std::max(upper[2], i->second.position[2]); + } + return; + } + + Real3 draw_position(std::shared_ptr& rng) const + { + FaceID fid; // will be discarded + const Real3 retval = this->draw_position(rng, fid); + return retval; + } + + //XXX This function randomly choose a face and does not consider the + // initial value of `fid`. An ID of randomly-chosen face will be + // written in `fid` when it returns. + Real3 draw_position(std::shared_ptr& rng, + FaceID& fid) const + { + Real draw_triangle = rng->uniform(0.0, total_area_); + + for(const auto& fidf : this->faces_) + { + const face_data& fd = fidf.second; + + draw_triangle -= fd.triangle.area(); + if(draw_triangle <= 0.0) + { + fid = fidf.first; + return fd.triangle.draw_position(rng); + } + } + + // if draw_triangle was positive throughout the loop, + // maybe because of numerical error, put it on the last face. + fid = this->faces_.back().first; + return faces_.back().second.triangle.draw_position(rng); + } + + // XXX This function considers `fid`. + Real3 draw_position_on_face(std::shared_ptr& rng, + const FaceID& fid) const + { + return this->triangle_at(fid).draw_position(rng); + } + + // to save/load the shape ------------------------------------------------// + + void reset(const Real3& edge_lengths) + { + this->edge_length_ = edge_lengths; + return; + } + + std::vector triangles() const + { + std::vector retval; + retval.reserve(this->faces_.size()); + for(const auto& f : this->faces_) + { + retval.push_back(f.second.triangle); + } + return retval; + } + +#ifdef WITH_HDF5 + void save_hdf5(H5::Group* root) const + { + save_polygon_hdf5(*this, root); + } + void load_hdf5(const H5::Group& root) + { + load_polygon_hdf5(root, this); + } +#endif + + // Boundary condition stuff ----------------------------------------------// + + Real3 const& edge_lengths() const throw() {return this->edge_length_;} + + // restrict position inside of the boundary. + Real3 apply_boundary(const Real3& pos) const + { + return modulo(pos, edge_length_); + } + + // transpose pos1 relative to pos2 + Real3 periodic_transpose(Real3 pos1, const Real3& pos2) const + { + const Real3 dpos = pos2 - pos1; + const Real3 half = edge_length_ * 0.5; + if (half[0] < dpos[0]) {pos1[0] += edge_length_[0];} + else if(dpos[0] < -half[0]) {pos1[0] -= edge_length_[0];} + if (half[1] < dpos[1]) {pos1[1] += edge_length_[1];} + else if(dpos[1] < -half[1]) {pos1[1] -= edge_length_[1];} + if (half[2] < dpos[2]) {pos1[2] += edge_length_[2];} + else if(dpos[2] < -half[2]) {pos1[2] -= edge_length_[2];} + return pos1; + } + + bool is_inside_of_boundary(const Real3& pos) const + { + const Real3& edge = this->edge_length_; + if (edge[0] < pos[0]) {return false;} + else if( pos[0] < 0.0) {return false;} + if (edge[1] < pos[1]) {return false;} + else if( pos[1] < 0.0) {return false;} + if (edge[2] < pos[2]) {return false;} + else if( pos[2] < 0.0) {return false;} + return true; + } + + // size stuff + + Real total_area() const throw() {return total_area_;} + std::size_t face_size() const throw() {return faces_.size();} + std::size_t edge_size() const throw() {return edges_.size();} + std::size_t vertex_size() const throw() {return vertices_.size();} + + std::vector list_vertex_ids() const + { + std::vector retval; retval.reserve(this->vertex_size()); + for(const auto& vidv : this->vertices_) + { + retval.push_back(vidv.first); + } + return retval; + } + std::vector list_face_ids() const + { + std::vector retval; retval.reserve(this->face_size()); + for(const auto& fidf : this->faces_) + { + retval.push_back(fidf.first); + } + return retval; + } + std::vector list_edge_ids() const + { + std::vector retval; retval.reserve(this->edge_size()); + for(const auto& eide : this->edges_) + { + retval.push_back(eide.first); + } + return retval; + } + + boost::optional + find_vertex(const Real3& pos) const + { + const Real tol_rel2 = relative_tolerance * relative_tolerance; + const Real tol_abs2 = absolute_tolerance * absolute_tolerance; + + for(const auto& vidv : this->vertices_) + { + const vertex_data& vd = vidv.second; + const Real dist_sq = length_sq( + this->periodic_transpose(vd.position, pos) - pos); + + if(dist_sq < tol_abs2 || dist_sq < length_sq(pos) * tol_rel2) + { + return vidv.first; + } + } + return boost::none; + } + + boost::optional + find_edge(const VertexID start, const VertexID stop) const + { + const vertex_data& vd = this->vertex_at(start); + for(std::vector >::const_iterator + i(vd.outgoing_edges.begin()), e(vd.outgoing_edges.end()); i!=e; ++i) + { + const EdgeID eid = i->first; + if(this->target_of(eid) == stop) + { + return eid; + } + } + return boost::none; + } + + boost::optional + find_face(const VertexID v1, const VertexID v2, + const VertexID v3) const + { + const std::vector& outs = this->outgoing_edges(v1); + for(typename std::vector::const_iterator + i(outs.begin()), e(outs.end()); i!=e; ++i) + { + if(target_of(*i) == v2 && target_of(next_of(*i)) == v3) + { + return face_of(*i); + } + if(target_of(*i) == v3 && target_of(next_of(*i)) == v2) + { + return face_of(*i); + } + } + return boost::none; + } + + + private: + + vertex_data const& vertex_at(const VertexID& vid) const + { + return this->vertices_.at(vid).second; + } + face_data const& face_at(const FaceID& fid) const + { + return this->faces_.at(fid).second; + } + edge_data const& edge_at(const EdgeID& eid) const + { + return this->edges_.at(eid).second; + } + + vertex_data& vertex_at(const VertexID& vid) + { + return this->vertices_.at(vid).second; + } + face_data& face_at(const FaceID& fid) + { + return this->faces_.at(fid).second; + } + edge_data& edge_at(const EdgeID& eid) + { + return this->edges_.at(eid).second; + } + + // ----------------------------------------------------------------------- + // list_faces_within_radius_impl and its query + + template + struct IntersectionQuery + { + Real3 center; + Real radius; + Filter ignores; + + IntersectionQuery(const Real3& c, const Real r, Filter f) noexcept + : center(c), radius(r), ignores(std::move(f)) + {} + IntersectionQuery(const IntersectionQuery&) = default; + IntersectionQuery(IntersectionQuery&&) = default; + IntersectionQuery& operator=(const IntersectionQuery&) = default; + IntersectionQuery& operator=(IntersectionQuery&&) = default; + ~IntersectionQuery() = default; + + // If it does not matches, return boost::none. + // If it matches, return pairof(pidp, distance). + boost::optional, Real>> + operator()(const std::pair& fidp, const PeriodicBoundary& pbc) const noexcept + { + if(ignores(fidp.first)){return boost::none;} + + const auto dist_sq = distance_sq_point_Triangle( + center, fidp.second.triangle, pbc); + + if(dist_sq <= this->radius * this->radius) + { + return std::make_pair( + std::make_pair(fidp.first, fidp.second.triangle), + std::sqrt(dist_sq)); + } + return boost::none; + } + + bool operator()(const AABB& box, const PeriodicBoundary& pbc) const noexcept + { + return this->distance_sq(box, this->center, pbc) <= + this->radius * this->radius; + } + + // ------------------------------------------------------------------- + // AABB-sphere distance calculation under the PBC + Real distance_sq(const AABB& box, Real3 pos, const PeriodicBoundary& pbc) const noexcept + { + pos = pbc.periodic_transpose(pos, (box.upper() + box.lower()) * 0.5); + + Real dist_sq = 0; + for(std::size_t i=0; i<3; ++i) + { + const auto v = pos[i]; + if(v < box.lower()[i]) + { + dist_sq += (v - box.lower()[i]) * (v - box.lower()[i]); + } + else if(box.upper()[i] < v) + { + dist_sq += (v - box.upper()[i]) * (v - box.upper()[i]); + } + } + return dist_sq; + } + }; + template + static IntersectionQuery make_intersection_query( + const Real3& c, const Real r, Filter&& f) + { + return IntersectionQuery(c, r, std::forward(f)); + } + + template + std::vector, Real>> + list_faces_within_radius_impl( + const Real3& pos, const Real& radius, Filter&& filter) const + { + std::vector, Real>> retval; + + this->faces_.query(make_intersection_query( + pos, radius, std::forward(filter) + ), std::back_inserter(retval)); + + std::sort(retval.begin(), retval.end(), + utils::pair_second_element_comparator, Real>{}); + + return retval; + } + + private: + + Real total_area_; + Real3 edge_length_; // boundary({0,0,0}, {edge_length}) + + SerialIDGenerator vertex_idgen_; + SerialIDGenerator face_idgen_; + SerialIDGenerator edge_idgen_; + + vertex_container_type vertices_; + face_container_type faces_; + edge_container_type edges_; +}; + +/********************** free functions to use a Polygon **********************/ + +namespace polygon +{ + +template +inline Real distance(const Polygon& p, + const std::pair& p1, const std::pair& p2) +{ + return p.distance(p1, p2); +// const Real d12 = p.distance(p1, p2); +// const Real d21 = p.distance(p2, p1); +// if(std::abs(d12 / d21) - 1.0 > 1e-12) +// { +// std::cerr << ""distance btw 1-2 = "" << std::setw(20) << d12 << "", 2-1 = "" << std::setw(20) << d21 +// << "", the difference = "" << std::setw(20) << std::abs(d12 / d21 - 1.0); +// std::cerr << "", p1 = ("" << p1.first << "", "" << p1.second +// << ""), p2 = ("" << p2.first << "", "" << p2.second +// << ')' << std::endl; +// } +// return std::min(d12, d21); +} + +template +inline Real distance_sq(const Polygon& p, + const std::pair& p1, const std::pair& p2) +{ + return p.distance_sq(p1, p2); +// const Real d12 = p.distance_sq(p1, p2); +// const Real d21 = p.distance_sq(p2, p1); +// if(std::abs(d12 / d21) - 1.0 > 1e-12) +// { +// std::cerr << ""distance_sq btw 1-2 = "" << std::setw(20) << d12 << "", 2-1 = "" << std::setw(20) << d21 +// << "", the difference = "" << std::setw(20) << std::abs(d12 / d21 - 1.0); +// std::cerr << "", p1 = ("" << p1.first << "", "" << p1.second +// << ""), p2 = ("" << p2.first << "", "" << p2.second +// << ')' << std::endl; +// } +// return std::min(d12, d21); +} + +template +inline Real3 direction(const Polygon& p, + const std::pair& p1, const std::pair& p2) +{ + return p.direction(p1, p2); +} + +inline std::pair travel(const Polygon& p, + const std::pair& pos, const Real3& disp) +{ + return p.travel(pos, disp); +} + +inline std::pair travel(const Polygon& p, + const std::pair& pos, const Real3& disp, + const std::size_t edge_restraint) +{ + return p.travel(pos, disp, edge_restraint); +} + +// for sGFRD +inline std::pair +roll(const Polygon& poly, + const std::pair& pos, + const VertexID vid, const Real r, const Real theta_) +{ + const Real3 vpos = poly.periodic_transpose(poly.position_at(vid), pos.first); + if(theta_ == 0.0) + { + const Real3 disp = pos.first - vpos; + const Real3 nwpos = poly.apply_boundary(vpos + disp * (r / length(disp))); + assert(::ecell4::is_inside( + ::ecell4::to_barycentric(nwpos, poly.triangle_at(pos.second)))); + return std::make_pair(nwpos, pos.second); + } + + const Real apex_angle = poly.apex_angle_at(vid); + assert(std::abs(theta_) < apex_angle); + + std::vector > const& outedges = + poly.outgoing_edge_and_angles(vid); + + std::vector >::const_iterator current_edge; + Real current_angle = 0.0; + for(std::vector >::const_iterator + i(outedges.begin()), e(outedges.end()); i!=e; ++i) + { + if(poly.face_of(i->first) == pos.second) + { + current_edge = i; + break; + } + current_angle += i->second; + } + current_angle += calc_angle( + poly.direction_of(current_edge->first), pos.first - vpos); + + const Real theta = ::ecell4::modulo(current_angle + theta_, apex_angle); +// std::cerr << ""initial position = "" << pos.first << std::endl; +// std::cerr << ""initial first = "" << pos.second << "", "" << poly.triangle_at(pos.second) << std::endl; +// std::cerr << ""current_angle = "" << current_angle << "", theta_ = "" << theta_ +// << "", apex_angle = "" << apex_angle << std::endl; +// std::cerr << ""theta = "" << theta << std::endl; + + current_angle = 0.0; + for(std::vector >::const_iterator + i(outedges.begin()), e(outedges.end()); i!=e; ++i) + { +// { +// std::cerr << ""face "" << poly.face_of(i->first) << "" = "" +// << poly.triangle_at(poly.face_of(i->first)) << std::endl; +// std::cerr << ""angle around vtx "" << vid << "" at "" << vpos << "" = "" +// << i->second << std::endl; +// } + + const Real next_angle = current_angle + i->second; + if(theta < next_angle) + { + const FaceID next_fid = poly.face_of(i->first); + const Real3& normal = poly.triangle_at(next_fid).normal(); + const Real diff_angle = theta - current_angle; + const Real3 direction = rotate( + diff_angle, normal, poly.direction_of(i->first)); + const Real3 next_pos = poly.apply_boundary( + vpos + direction * (r / length(direction))); + + if(!::ecell4::is_inside( + to_barycentric(next_pos, poly.triangle_at(next_fid)))) + { + std::cerr << ""position = "" << next_pos << "", face "" << next_fid + << "" = "" << poly.triangle_at(next_fid) << std::endl; + assert(false); + } + return std::make_pair(next_pos, next_fid); + } + current_angle = next_angle; + } + throw std::logic_error(""ecell4::polygon::roll never reach here""); +} + +} // polygon + +// for error message generation in PeriodicRTree +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const Polygon::face_data& fd) +{ + os << fd.triangle; + return os; +} + + +} // ecell4 +#endif// ECELL4_POLYGON +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Sphere.cpp",".cpp","2464","140","#include ""Sphere.hpp"" +#include ""collision.hpp"" + + +namespace ecell4 +{ + +Sphere::Sphere() + : center_(), radius_() +{ + ; +} + +Sphere::Sphere(const Real3& center, const Real radius) + : center_(center), radius_(radius) +{ + ; +} + +Sphere::Sphere(const Sphere& rhs) + : center_(rhs.center()), radius_(rhs.radius()) +{ + ; +} + +const Real& Sphere::radius() const +{ + return radius_; +} + +const Real3& Sphere::center() const +{ + return center_; +} + +Real Sphere::distance(const Real3& coord) const +{ + return length(coord - center_) - radius_; +} + +Real Sphere::is_inside(const Real3& coord) const +{ + return distance(coord); +} + +SphericalSurface Sphere::surface() const +{ + return SphericalSurface(center_, radius_); +} + +Real3 Sphere::draw_position( + std::shared_ptr& rng) const +{ + if (radius_ <= 0.0) + { + return center_; + } + + while (true) + { + const Real x(rng->uniform(-radius_, +radius_)); + const Real y(rng->uniform(-radius_, +radius_)); + const Real z(rng->uniform(-radius_, +radius_)); + const Real3 dir(x, y, z); + const Real3 pos(dir + center_); + if (is_inside(pos) <= 0.0) + { + return pos; + } + } + + ; // never reach here +} + +bool Sphere::test_AABB(const Real3& l, const Real3& u) const +{ + return collision::test_sphere_AABB(*this, l, u); +} + +SphericalSurface::SphericalSurface() + : center_(), radius_() +{ + ; +} + +SphericalSurface::SphericalSurface(const Real3& center, const Real radius) + : center_(center), radius_(radius) +{ + ; +} + +SphericalSurface::SphericalSurface(const SphericalSurface& rhs) + : center_(rhs.center()), radius_(rhs.radius()) +{ + ; +} + +const Real& SphericalSurface::radius() const +{ + return radius_; +} + +const Real3& SphericalSurface::center() const +{ + return center_; +} + +Real SphericalSurface::distance(const Real3& coord) const +{ + return length(coord - center_) - radius_; +} + +Real SphericalSurface::is_inside(const Real3& coord) const +{ + return distance(coord); +} + +Sphere SphericalSurface::inside() const +{ + return Sphere(center_, radius_); +} + +Real3 SphericalSurface::draw_position( + std::shared_ptr& rng) const +{ + if (radius_ <= 0.0) + { + return center_; + } + + return rng->direction3d(radius_) + center_; +} + +bool SphericalSurface::test_AABB(const Real3& l, const Real3& u) const +{ + return collision::test_shell_AABB(*this, l, u); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/MoleculePool.hpp",".hpp","5522","214","#ifndef ECELL4_MOLECULE_POOL_HPP +#define ECELL4_MOLECULE_POOL_HPP + +#include ""VoxelPool.hpp"" + +namespace ecell4 +{ + +class MoleculePool : public VoxelPool +{ +public: + typedef VoxelPool base_type; + + typedef std::vector container_type; + typedef container_type::const_iterator const_iterator; + typedef container_type::iterator iterator; + +public: + MoleculePool(const Species &species, std::weak_ptr location) + : base_type(species, location) + { + ; + } + + virtual ~MoleculePool() { ; } + + virtual voxel_type_type const voxel_type() const { return DEFAULT; } + +public: + virtual void add_voxel(const coordinate_id_pair_type &info) + { + voxels_.push_back(info); + } + + virtual void replace_voxel(const coordinate_type &from_coord, + const coordinate_type &to_coord, + const std::size_t candidate = 0) + { + container_type::iterator itr(find(from_coord, candidate)); + if (itr == voxels_.end()) + { + std::cerr << ""from_coord = "" << from_coord << std::endl; + throw NotFound(""no corresponding coordinate was found.""); + } + + (*itr).coordinate = to_coord; + } + + virtual bool remove_voxel_if_exists(const coordinate_type &coord) + { + container_type::iterator itr(find(coord)); + if (itr != voxels_.end()) + { + this->remove_voxel(itr); + return true; + } + return false; + } + + virtual const ParticleID get_particle_id(const coordinate_type &coord) const + { + container_type::const_iterator i(this->find(coord)); + if (i == voxels_.end()) + { + throw NotFound(""No corresponding ParticleID was found.""); + } + return (*i).pid; + } + +public: + void remove_voxel(const container_type::iterator &position) + { + // voxels_.erase(position); + (*position) = voxels_.back(); + voxels_.pop_back(); + } + + coordinate_id_pair_type pop(const coordinate_type &coord) + { + container_type::iterator position(this->find(coord)); + const coordinate_id_pair_type info(*position); + this->remove_voxel(position); + return info; + } + + void replace_voxel(const coordinate_type &from_coord, + const coordinate_id_pair_type &to_info) + { + container_type::iterator itr(find(from_coord)); + if (itr == voxels_.end()) + { + throw NotFound(""no corresponding coordinate was found.""); + } + + (*itr) = to_info; + } + + void swap(const container_type::iterator &a, + const container_type::iterator &b) + { + if (a == b) + { + return; + } + + const container_type::value_type info(*b); + (*b) = (*a); + (*a) = info; + } + + coordinate_id_pair_type &at(const Integer &index) + { + return voxels_.at(index); + } + + coordinate_id_pair_type const &at(const Integer &index) const + { + return voxels_.at(index); + } + + coordinate_id_pair_type &operator[](const Integer &n) { return voxels_[n]; } + + coordinate_id_pair_type const &operator[](const Integer &n) const + { + return voxels_[n]; + } + + const Integer size() const { return voxels_.size(); } + + void shuffle(RandomNumberGenerator &rng) { ecell4::shuffle(rng, voxels_); } + + container_type::iterator begin() { return voxels_.begin(); } + + container_type::const_iterator begin() const { return voxels_.begin(); } + + container_type::iterator end() { return voxels_.end(); } + + container_type::const_iterator end() const { return voxels_.end(); } + + container_type::iterator find(const ParticleID &pid) + { + container_type::iterator itr; + for (itr = voxels_.begin(); itr != voxels_.end(); ++itr) + { + if ((*itr).pid == pid) + { + break; + } + } + return itr; + } + + container_type::const_iterator find(const ParticleID &pid) const + { + container_type::const_iterator itr; + for (itr = voxels_.begin(); itr != voxels_.end(); ++itr) + { + if ((*itr).pid == pid) + { + break; + } + } + return itr; + } + +protected: + container_type::iterator find(coordinate_type coord, + const std::size_t candidate = 0) + { + container_type::iterator itr; + if (candidate < voxels_.size()) + { + itr = voxels_.begin() + candidate; + if ((*itr).coordinate == coord) + return itr; + } + for (itr = voxels_.begin(); itr != voxels_.end(); ++itr) + { + if ((*itr).coordinate == coord) + { + break; + } + } + return itr; + } + + container_type::const_iterator find(coordinate_type coord, + const std::size_t candidate = 0) const + { + container_type::const_iterator itr; + if (candidate < voxels_.size()) + { + itr = voxels_.begin() + candidate; + if ((*itr).coordinate == coord) + return itr; + } + for (itr = voxels_.begin(); itr != voxels_.end(); ++itr) + { + if ((*itr).coordinate == coord) + { + break; + } + } + return itr; + } + +protected: + container_type voxels_; +}; + +} // namespace ecell4 + +#endif +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/VoxelSpaceBase.cpp",".cpp","7974","316","#include ""Context.hpp"" +#include ""VoxelSpaceBase.hpp"" + +namespace ecell4 +{ + +/* + * CompartmentSpace Traits + */ + +std::vector VoxelSpaceBase::list_species() const +{ + std::vector keys; + for(const auto& kv : voxel_pools_) + { + keys.push_back(kv.first); + } + for(const auto& kv : molecule_pools_) + { + keys.push_back(kv.first); + } + return keys; +} + +Integer VoxelSpaceBase::num_molecules(const Species &sp) const +{ + Integer count(0); + SpeciesExpressionMatcher sexp(sp); + + { + const auto cnt = sexp.count(vacant_->species()); + if (cnt > 0) + { + count += vacant_->size() * cnt; + } + } + + for (voxel_pool_map_type::const_iterator itr(voxel_pools_.begin()); + itr != voxel_pools_.end(); ++itr) + { + const Integer cnt(sexp.count((*itr).first)); + if (cnt > 0) + { + count += itr->second->size() * cnt; + } + } + + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + { + const Integer cnt(sexp.count((*itr).first)); + if (cnt > 0) + { + const std::shared_ptr &vp((*itr).second); + count += vp->size() * cnt; + } + } + return count; +} + +/* + * VoxelSpace Traits + */ + +bool VoxelSpaceBase::has_voxel(const ParticleID &pid) const +{ + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + { + const std::shared_ptr &vp((*itr).second); + if (vp->find(pid) != vp->end()) + return true; + } + return false; +} + +Integer VoxelSpaceBase::num_voxels_exact(const Species &sp) const +{ + if (sp == vacant_->species()) + { + return vacant_->size(); + } + + { + voxel_pool_map_type::const_iterator itr(voxel_pools_.find(sp)); + if (itr != voxel_pools_.end()) + { + return itr->second->size(); + } + } + + { + molecule_pool_map_type::const_iterator itr(molecule_pools_.find(sp)); + if (itr != molecule_pools_.end()) + { + const std::shared_ptr &vp((*itr).second); + return vp->size(); + } + } + + return 0; +} + +Integer VoxelSpaceBase::num_voxels(const Species &sp) const +{ + Integer count(0); + SpeciesExpressionMatcher sexp(sp); + + if (sexp.match(vacant_->species())) + { + count += vacant_->size(); + } + + for (voxel_pool_map_type::const_iterator itr(voxel_pools_.begin()); + itr != voxel_pools_.end(); ++itr) + { + if (sexp.match((*itr).first)) + { + count += itr->second->size(); + } + } + + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + { + if (sexp.match((*itr).first)) + { + const std::shared_ptr &vp((*itr).second); + count += vp->size(); + } + } + return count; +} + +Integer VoxelSpaceBase::num_voxels() const +{ + Integer count(0); + + if (vacant_->species().serial() != """") + { + count += vacant_->size(); + } + + for (voxel_pool_map_type::const_iterator itr(voxel_pools_.begin()); + itr != voxel_pools_.end(); ++itr) + { + count += itr->second->size(); + } + + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + { + const std::shared_ptr &vp((*itr).second); + count += vp->size(); + } + + return count; +} + +static inline void +push_voxels(std::vector &voxels, + const std::shared_ptr &voxel_pool) +{ + for (const auto &voxel : *voxel_pool) + { + voxels.push_back( + VoxelView(voxel.pid, voxel_pool->species(), voxel.coordinate)); + } +} + +std::vector VoxelSpaceBase::list_voxels() const +{ + std::vector retval; + + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + { + const std::shared_ptr &vp((*itr).second); + push_voxels(retval, vp); + } + + return retval; +} + +std::vector VoxelSpaceBase::list_voxels(const Species &sp) const +{ + std::vector retval; + SpeciesExpressionMatcher sexp(sp); + + for (molecule_pool_map_type::const_iterator itr(molecule_pools_.begin()); + itr != molecule_pools_.end(); ++itr) + if (sexp.match((*itr).first)) + push_voxels(retval, (*itr).second); + + return retval; +} + +std::vector +VoxelSpaceBase::list_voxels_exact(const Species &sp) const +{ + std::vector retval; + + molecule_pool_map_type::const_iterator itr(molecule_pools_.find(sp)); + if (itr != molecule_pools_.end()) + push_voxels(retval, (*itr).second); + return retval; +} + +std::shared_ptr VoxelSpaceBase::find_voxel_pool(const Species &sp) +{ + if (sp == vacant_->species()) + return vacant_; + + voxel_pool_map_type::iterator itr(voxel_pools_.find(sp)); + if (itr != voxel_pools_.end()) + { + return (*itr).second; + } + return find_molecule_pool(sp); // upcast +} + +std::shared_ptr +VoxelSpaceBase::find_voxel_pool(const Species &sp) const +{ + if (sp == vacant_->species()) + return vacant_; + + voxel_pool_map_type::const_iterator itr(voxel_pools_.find(sp)); + if (itr != voxel_pools_.end()) + { + return (*itr).second; + } + return find_molecule_pool(sp); // upcast +} + +bool VoxelSpaceBase::has_molecule_pool(const Species &sp) const +{ + return (molecule_pools_.find(sp) != molecule_pools_.end()); +} + +std::shared_ptr +VoxelSpaceBase::find_molecule_pool(const Species &sp) +{ + molecule_pool_map_type::iterator itr(molecule_pools_.find(sp)); + if (itr != molecule_pools_.end()) + { + return (*itr).second; // upcast + } + throw NotFound(""MoleculePool not found.""); +} + +std::shared_ptr +VoxelSpaceBase::find_molecule_pool(const Species &sp) const +{ + molecule_pool_map_type::const_iterator itr(molecule_pools_.find(sp)); + if (itr != molecule_pools_.end()) + { + return (*itr).second; // upcast + } + throw NotFound(""MoleculePool not found.""); +} + +bool VoxelSpaceBase::make_molecular_type(const Species &sp, + const std::string loc) +{ + molecule_pool_map_type::iterator itr(molecule_pools_.find(sp)); + if (itr != molecule_pools_.end()) + { + return false; + } + else if (voxel_pools_.find(sp) != voxel_pools_.end()) + { + throw IllegalState(""The given species is already assigned to the "" + ""VoxelPool with no voxels.""); + } + + std::shared_ptr vp( + new MoleculePool(sp, find_voxel_pool(Species(loc)))); + + std::pair retval( + molecule_pools_.insert(molecule_pool_map_type::value_type(sp, vp))); + + if (!retval.second) + { + throw AlreadyExists(""never reach here.""); + } + return retval.second; +} + +bool VoxelSpaceBase::make_structure_type(const Species &sp, + const std::string loc) +{ + voxel_pool_map_type::iterator itr(voxel_pools_.find(sp)); + if (itr != voxel_pools_.end()) + { + return false; + } + else if (molecule_pools_.find(sp) != molecule_pools_.end()) + { + throw IllegalState( + ""The given species is already assigned to the MoleculePool.""); + } + + std::shared_ptr vp( + new StructureType(sp, find_voxel_pool(Species(loc)))); + std::pair retval( + voxel_pools_.insert(voxel_pool_map_type::value_type(sp, vp))); + if (!retval.second) + { + throw AlreadyExists(""never reach here.""); + } + return retval.second; +} + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/triangle_geometry.hpp",".hpp","2469","86","#ifndef ECELL4_TRIANGLE_GEOMETRY +#define ECELL4_TRIANGLE_GEOMETRY +#include +#include +#include + +namespace ecell4 +{ + +inline Real3 centroid(const Triangle& tri) +{ + return (tri.vertices()[0] + tri.vertices()[1] + tri.vertices()[2]) * (1. / 3.); +} +inline Real3 centroid(const TriangleView& tri) +{ + return (tri.vertices(0) + tri.vertices(1) + tri.vertices(2)) * (1. / 3.); +} +inline Real3 centroid(const TriangleConstView& tri) +{ + return (tri.vertices(0) + tri.vertices(1) + tri.vertices(2)) * (1. / 3.); +} + +inline Real3 incenter(const Triangle& tri) +{ + const Real a = tri.lengths_of_edges()[1]; + const Real b = tri.lengths_of_edges()[2]; + const Real c = tri.lengths_of_edges()[0]; + const Real rabc = 1. / (a + b + c); + return (tri.vertices()[0] * a + tri.vertices()[1] * b + tri.vertices()[2] * c) * rabc; +} + +inline Real3 incenter(const TriangleView& tri) +{ + const Real a = length(tri.vertices(0)); + const Real b = length(tri.vertices(1)); + const Real c = length(tri.vertices(2)); + const Real rabc = 1. / (a + b + c); + return (tri.vertices(0) * a + tri.vertices(1) * b + tri.vertices(2) * c) * rabc; +} + +inline Real3 incenter(const TriangleConstView& tri) +{ + const Real a = length(tri.vertices(0)); + const Real b = length(tri.vertices(1)); + const Real c = length(tri.vertices(2)); + const Real rabc = 1. / (a + b + c); + return (tri.vertices(0) * a + tri.vertices(1) * b + tri.vertices(2) * c) * rabc; +} + +Real3 closest_point(const Real3&, const Triangle&); +Real3 closest_point(const Real3&, const TriangleView&); +Real3 closest_point(const Real3&, const TriangleConstView&); + +inline Real distance_sq(const Real3& pos, const Triangle& tri) +{ + return length_sq(closest_point(pos, tri) - pos); +} + +inline Real distance(const Real3& pos, const Triangle& tri) +{ + return std::sqrt(distance_sq(pos, tri)); +} + +inline Real distance_sq(const Real3& pos, const TriangleView& tri) +{ + return length_sq(closest_point(pos, tri) - pos); +} + +inline Real distance(const Real3& pos, const TriangleView& tri) +{ + return std::sqrt(distance_sq(pos, tri)); +} + +inline Real distance_sq(const Real3& pos, const TriangleConstView& tri) +{ + return length_sq(closest_point(pos, tri) - pos); +} + +inline Real distance(const Real3& pos, const TriangleConstView& tri) +{ + return std::sqrt(distance_sq(pos, tri)); +} + +} // ecell4 +#endif// ECELL4_TRIANGLE_GEOMETRY +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Model.cpp",".cpp","54","7","#include ""Model.hpp"" + +namespace ecell4 +{ + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/DynamicPriorityQueue.hpp",".hpp","14459","566","#ifndef ECELL4_DYNAMICPRIORITYQUEUE_HPP +#define ECELL4_DYNAMICPRIORITYQUEUE_HPP +// +// written by Koichi Takahashi based on the initial version by Eiichiro Adachi. +// modified by Mozoyoshi Koizumi +// + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#ifdef DEBUG +#include +#endif + +namespace ecell4 +{ + +template +struct default_id_generator +{ + typedef Tid_ identifier_type; + + default_id_generator(): next_() {} + + default_id_generator(identifier_type const& first): next_(first) {} + + identifier_type operator()() + { + return ++next_; + } + +protected: + identifier_type next_; +}; + + +template > +class persistent_id_policy +{ +public: + typedef Tid_ identifier_type; + typedef Tindex_ index_type; + typedef Tidgen_ identifier_generator; + +protected: + struct hasher + : public std::unary_function + { + std::size_t operator()(identifier_type value) const + { + return static_cast(value) ^ + static_cast( + value >> (sizeof(identifier_type) * 8 / 2)); + } + }; + typedef std::unordered_map index_map; + +public: + index_type index(identifier_type const& id) const + { + typename index_map::const_iterator i(index_map_.find(id)); + if (i == index_map_.end()) + { + throw std::out_of_range((boost::format(""%s: Key not found (%s)"") + % __FUNCTION__ % boost::lexical_cast(id)).str()); + // throw std::out_of_range((boost::format(""%s: Key not found (%s)"") + // % __PRETTY_FUNCTION__ % boost::lexical_cast(id)).str()); + } + return (*i).second; + } + + identifier_type push(index_type index) + { + const identifier_type id(idgen_()); + index_map_.insert(typename index_map::value_type(id, index)); + return id; + } + + void pop(index_type index, identifier_type id, identifier_type last_item_id) + { + index_map_[last_item_id] = index; + index_map_.erase(id); + } + + void clear() + { + index_map_.clear(); + } + +private: + index_map index_map_; + identifier_generator idgen_; +}; + +template +class volatile_id_policy +{ +public: + typedef Tindex_ identifier_type; + typedef Tindex_ index_type; + + index_type index(identifier_type const& id) const + { + return id; + } + + identifier_type push(index_type index) + { + return index; + } + + void pop(index_type, identifier_type, identifier_type) {} + + void clear() {} +}; + + +/** + Dynamic priority queue for items of type Titem_. + + When Tpolicy_ template parameter is persistent_id_policy, identifier_types assigned + to pushed items are persistent for the life time of this priority + queue. + + When Volatileidentifier_typePolicy template parameter is used as the Tpolicy_, + identifier_types are valid only until the next call of pop or push methods. + However, Volatileidentifier_typePolicy saves some memory and eliminates the + overhead incurred in pop/push methods. +*/ + +template, class Tpolicy_ = persistent_id_policy<> > +class DynamicPriorityQueue: private Tpolicy_ +{ +public: + typedef Tpolicy_ policy_type; + typedef typename policy_type::identifier_type identifier_type; + typedef typename policy_type::index_type index_type; + typedef Titem_ element_type; + typedef std::pair value_type; + typedef Tcomparator comparator_type; + +protected: + typedef std::vector value_vector; + typedef std::vector index_vector; + +public: + typedef typename value_vector::size_type size_type; + typedef typename value_vector::const_iterator iterator; + typedef typename value_vector::const_iterator const_iterator; + +public: + bool empty() const + { + return items_.empty(); + } + + size_type size() const + { + return items_.size(); + } + + void clear(); + + value_type const& top() const + { + return items_[top_index()]; + } + + value_type const& second() const + { + return items_[second_index()]; + } + + element_type const& get(identifier_type id) const + { + return items_[policy_type::index(id)].second; + } + + void pop() + { + pop_by_index(top_index()); + } + + void pop(identifier_type id) + { + pop_by_index(policy_type::index(id)); + } + + void replace(value_type const& item); + + identifier_type push(element_type const& item); + + element_type const& operator[](identifier_type id) const + { + return get(id); + } + + const_iterator begin() const + { + return items_.begin(); + } + + const_iterator end() const + { + return items_.end(); + } + + // self-diagnostic methods + bool check() const; // check all + bool check_size() const; + bool check_position_mapping() const; + bool check_heap() const; + + +protected: + index_type top_index() const + { + return heap_[0]; + } + + index_type second_index() const + { + if (size() <= 1) + { + throw std::out_of_range(""DynamicPriorityQueue::second_index():"" + "" item count less than 2.""); + } + + const index_type index1(heap_[1]); + + if (size() == 2) + { + return index1; + } + + const index_type index2(heap_[2]); + if (comp(items_[index1].second, items_[index2].second)) + { + return index1; + } + else + { + return index2; + } + } + + void pop_by_index(index_type index); + + void move(index_type index) + { + const index_type pos(position_vector_[index]); + move_pos(pos); + } + + void move_top() + { + move_down_pos(0); + } + + void move_pos(index_type pos); + + void move_up(index_type index) + { + const index_type position(position_vector_[index]); + move_up_pos(position); + } + + void move_down(index_type index) + { + const index_type position(position_vector_[index]); + move_down_pos(position); + } + + + void move_up_pos(index_type position, index_type start = 0); + void move_down_pos(index_type position); + + void move_up_pos_impl(index_type position, index_type start = 0); + void move_down_pos_impl(index_type position); + +private: + value_vector items_; + index_vector heap_; + index_vector position_vector_; + + comparator_type comp; +}; + +template +inline void DynamicPriorityQueue::clear() +{ + items_.clear(); + heap_.clear(); + position_vector_.clear(); + policy_type::clear(); +} + + +template +inline void DynamicPriorityQueue::move_pos(index_type pos) +{ + const index_type index(heap_[pos]); + const value_type& item(items_[index]); + const index_type succ(2 * pos + 1); + if (succ < size()) + { + if (comp(items_[heap_[succ]].second, item.second) || (succ + 1 < size() && comp(items_[heap_[succ + 1]].second, item.second))) + { + move_down_pos_impl(pos); + return; + } + } + + move_up_pos(pos); +} + +template +inline void DynamicPriorityQueue::move_up_pos(index_type position, index_type start) +{ + if (position == 0) + return; + + const index_type index(heap_[position]); + const value_type& item(items_[index]); + + const index_type pred((position - 1) / 2); + const index_type predindex_type(heap_[pred]); + + if (comp(item.second, items_[predindex_type].second)) + { + move_up_pos_impl(position, start); + } +} + + +template +inline void DynamicPriorityQueue::move_down_pos(index_type position) +{ + const index_type index(heap_[position]); + const value_type& item(items_[index]); + + const index_type succ(2 * position + 1); + if (succ < size()) + { + if (comp(items_[heap_[succ]].second, item.second) || (succ + 1 < size() && comp(items_[heap_[succ + 1]].second, item.second))) + { + move_down_pos_impl(position); + } + } +} + +template +inline void DynamicPriorityQueue::move_up_pos_impl(index_type position, index_type start) +{ + const index_type index(heap_[position]); + const value_type& item(items_[index]); + + if (position <= start) + { + return; + } + + index_type pos(position); + index_type pred((pos - 1) / 2); + index_type predindex_type(heap_[pred]); + + do + { + heap_[pos] = predindex_type; + position_vector_[predindex_type] = pos; + pos = pred; + + if (pos <= start) + { + break; + } + + pred = (pos - 1) / 2; + predindex_type = heap_[pred]; + + } while (! comp(items_[predindex_type].second, item.second)); + + heap_[pos] = index; + position_vector_[index] = pos; +} + + +template +inline void DynamicPriorityQueue::move_down_pos_impl(index_type position) +{ + const index_type index(heap_[position]); + + index_type succ(2 * position + 1); + index_type pos(position); + while (succ < size()) + { + const index_type right_pos(succ + 1); + if (right_pos < size() && !comp(items_[heap_[succ]].second, items_[heap_[right_pos]].second)) + { + succ = right_pos; + } + + heap_[pos] = heap_[succ]; + position_vector_[heap_[pos]] = pos; + pos = succ; + succ = 2 * pos + 1; + } + + heap_[pos] = index; + position_vector_[index] = pos; + + move_up_pos(pos, position); +} + + + +template +inline typename DynamicPriorityQueue::identifier_type +DynamicPriorityQueue::push(Titem_ const& item) +{ + const index_type index(items_.size()); + const identifier_type id(policy_type::push(index)); + items_.push_back(value_type(id, item)); + // index == pos at this time. + heap_.push_back(index); + position_vector_.push_back(index); + move_up_pos(index); + return id; +} + + +template +inline void DynamicPriorityQueue::pop_by_index(index_type index) +{ + value_type& item(items_[index]); + // 1. update index<->identifier_type mapping. + policy_type::pop(index, item.first, items_.back().first); + + // 2. pop the item from the items_. + using std::swap; // ADL-based specialization + swap(item, items_.back()); + items_.pop_back(); + + const index_type removed_pos(position_vector_[index]); + const index_type moved_pos(position_vector_.back()); + + // 3. swap position_vector_[end] and position_vector_[index] + position_vector_[index] = moved_pos; + heap_[moved_pos] = index; + + // 4. if heap_[end] and heap_[removed] do not overlap, + // swap these, pop back, and update the heap_. + if (removed_pos != heap_.size() - 1) + { + heap_[removed_pos] = heap_.back(); + position_vector_[heap_.back()] = removed_pos; + + position_vector_.pop_back(); + heap_.pop_back(); + + move_pos(removed_pos); + } + else // if heap_[end] and heap_[removed] are the same, simply pop back. + { + position_vector_.pop_back(); + heap_.pop_back(); + } +} + +template +inline void DynamicPriorityQueue::replace(value_type const& value) +{ + const index_type index(policy_type::index(value.first)); + items_[index].second = value.second; + move(index); +} + +template +inline bool DynamicPriorityQueue::check() const +{ + bool result(true); + + result = result && check_size(); + result = result && check_position_mapping(); + result = result && check_heap(); + + return result; +} + + +template +inline bool DynamicPriorityQueue::check_size() const +{ + bool result(true); + + // check sizes of data structures. + result = result && items_.size() == size(); + result = result && heap_.size() == size(); + result = result && position_vector_.size() == size(); + + return result; +} + + +template +inline bool DynamicPriorityQueue::check_position_mapping() const +{ + bool result(true); + + // assert correct mapping between the heap_ and the position_vector_. + for (index_type i(0); i < size(); ++i) + { + result = result && heap_[i] < size(); + result = result && position_vector_[i] < size(); + result = result && heap_[position_vector_[i]] == i; + } + + return result; +} + +template +inline bool DynamicPriorityQueue::check_heap() const +{ + bool result(true); + + // assert correct ordering of items in the heap_. + + for (index_type pos(0); pos < size(); ++pos) + { + const value_type& item(items_[heap_[pos]]); + + const index_type succ(pos * 2 + 1); + if (succ < size()) + { + result = result && + comp(item.second, items_[heap_[succ]].second); + + const index_type right_pos(succ + 1); + if (right_pos < size()) + { + result = result && comp(item.second, items_[heap_[right_pos]].second); + } + } + + } + + return result; +} + +} // ecell4 + +#endif // ECELL4_DYNAMICPRIORITYQUEUE_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/SimulatorFactory.hpp",".hpp","1861","89","#ifndef ECELL4_SIMULATOR_FACTORY_HPP +#define ECELL4_SIMULATOR_FACTORY_HPP + +#include ""WorldInterface.hpp"" +#include ""Model.hpp"" +#include ""Simulator.hpp"" +#include ""extras.hpp"" +#include ""functions.hpp"" + + +namespace ecell4 +{ + +template +class SimulatorFactory +{ +public: + + typedef Tworld_ world_type; + typedef Tsim_ simulator_type; + +public: + + SimulatorFactory() + { + ; // do nothing + } + + virtual ~SimulatorFactory() + { + ; // do nothing + } + + world_type* world(const Real3& edge_lengths = ones()) const + { + return create_world(edge_lengths); + } + + world_type* world(const Real volume) const + { + return world(ones() * cbrt(volume)); + } + + world_type* world(const std::string& filename) const + { + return new world_type(filename); + } + + world_type* world(const std::shared_ptr& m) const + { + return extras::generate_world_from_model(*this, m); + } + + simulator_type* simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const + { + return create_simulator(w, m); + } + + simulator_type* simulator(const std::shared_ptr& w) const + { + if (std::shared_ptr bound_model = w->lock_model()) + { + return create_simulator(w, bound_model); + } + else + { + throw std::invalid_argument(""A world must be bound to a model.""); + } + } + +protected: + + virtual world_type* create_world(const Real3& edge_lengths) const + { + return new world_type(edge_lengths); + } + + virtual simulator_type* create_simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const + { + return new simulator_type(w, m); + } +}; + +} // ecell4 + +#endif /* ECELL4_SIMULATOR_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/AABB.cpp",".cpp","1016","47","#include ""AABB.hpp"" +#include ""collision.hpp"" + + +namespace ecell4 +{ + +Real AABB::distance_sq(const Real3 pos) const +{ + return collision::distance_sq_point_AABB(pos, *this); +} + +Real AABB::distance(const Real3& pos) const +{ + return sqrt(distance_sq(pos)); +} + +Real3 AABB::draw_position( + std::shared_ptr& rng) const +{ + const Real3 pos( + rng->uniform(lower_[0], upper_[0]), + rng->uniform(lower_[1], upper_[1]), + rng->uniform(lower_[2], upper_[2])); + return pos; +} + +bool AABB::test_AABB(const Real3& l, const Real3& u) const +{ + return collision::test_AABB_AABB(lower_, upper_, l, u); +} + +bool AABB::test_segment(const Real3& p0, const Real3& p1) const +{ + return collision::test_segment_AABB(p0, p1, lower_, upper_); +} + +std::pair AABB::intersect_ray(const Real3& p, const Real3& d) const +{ + Real tmin; + Real3 q; + const bool retval(collision::intersect_ray_AABB(p, d, lower_, upper_, tmin, q)); + return std::make_pair(retval, tmin); +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Model.hpp",".hpp","7451","241","#ifndef ECELL4_MODEL_HPP +#define ECELL4_MODEL_HPP + +#include ""types.hpp"" +#include ""Species.hpp"" +#include ""ReactionRule.hpp"" +#include ""exceptions.hpp"" + + +namespace ecell4 +{ + +class Model +{ +public: + + typedef std::vector species_container_type; + typedef std::vector reaction_rule_container_type; + +public: + + virtual ~Model() + { + ; + } + + // ModelTraits + + /** + * a fundamental function to query unimolecular reaction rules from a reactant. + * this must be overloaded by any sub classes of Model. + * @param species Species of a reactant + * @return the vector of ReactionRule(s) + */ + virtual std::vector query_reaction_rules( + const Species& sp) const = 0; + + /** + * a fundamental function to query bimolecular reaction rules from reactants. + * this must be overloaded by any sub classes of Model. + * @param species1 Species of the first reactant + * @param species2 Species of the second reactant + * @return the vector of ReactionRule(s) + */ + virtual std::vector query_reaction_rules( + const Species& sp1, const Species& sp2) const = 0; + + virtual Integer apply(const Species& pttrn, const Species& sp) const = 0; + virtual std::vector apply( + const ReactionRule& rr, + const ReactionRule::reactant_container_type& reactants) const = 0; + + // NetworkModelTraits + + virtual bool is_static() const + { + return false; + } + + virtual bool update_species_attribute(const Species& sp) + { + throw NotSupported( + ""update_species_attribute is not supported in this model class""); + } + + /** + * add attributes of species to the model. + * this function is a part of the trait of Model. + * @param species a new Species + */ + virtual void add_species_attribute(const Species& sp, const bool proceed = false) + { + throw NotSupported( + ""add_species_attribute is not supported in this model class""); + } + + /** + * return if a species attribute is in the model, or not. + * this function is a part of the trait of Model. + * @param species a Species + * @return if the species exists, or not + */ + virtual bool has_species_attribute(const Species& sp) const + { + throw NotSupported( + ""has_species_attribute is not supported in this model class""); + } + + /** + * remove attributes of species in the model. + * this function is a part of the trait of Model. + * @param species a new Species + */ + virtual void remove_species_attribute(const Species& sp) + { + throw NotSupported( + ""remove_species_attribute is not supported in this model class""); + } + + /** + * apply attributes of species to the given species. + * this function is a part of the trait of Model. + * @param species an original Species + */ + virtual Species apply_species_attributes(const Species& sp) const + { + throw NotSupported( + ""apply_species_attributes is not supported in this model class""); + } + + Species create_species(const std::string& name) const + { + return apply_species_attributes(Species(name)); + } + + /** + * add a reaction rule to the model. + * this function is a part of the trait of Model. + * @param rr a new ReactionRule + * @return if the reaction rule is not registered yet. + */ + virtual void add_reaction_rule(const ReactionRule& rr) + { + throw NotSupported( + ""add_reaction_rule is not supported in this model class""); + } + + /** + * remove a reaction rule in the model. + * this function is a part of the trait of Model. + * @param rr a new ReactionRule + */ + virtual void remove_reaction_rule(const ReactionRule& rr) + { + throw NotSupported( + ""remove_reaction_rule is not supported in this model class""); + } + + /** + * return if a reaction rule is in the model, or not. + * this function is a part of the trait of Model. + * @param rr a reaction rule + * @return if the reaction rule exists, or not + */ + virtual bool has_reaction_rule(const ReactionRule& rr) const + { + throw NotSupported( + ""has_reaction_rule is not supported in this model class""); + } + + virtual const reaction_rule_container_type& reaction_rules() const = 0; + virtual const species_container_type& species_attributes() const = 0; + virtual const std::vector& species_attributes_proceed() const = 0; + + const Integer num_reaction_rules() const + { + return this->reaction_rules().size(); + } + + virtual std::shared_ptr expand( + const std::vector& sp, const Integer max_itr, + const std::map& max_stoich) const = 0; + virtual std::shared_ptr expand( + const std::vector& sp, const Integer max_itr) const = 0; + virtual std::shared_ptr expand( + const std::vector& sp) const = 0; + + const std::vector list_species() const + { + std::vector retval; + + // const species_container_type& attrs(species_attributes()); + // std::copy(attrs.begin(), attrs.end(), std::back_inserter(retval)); //XXX: This copies attributes too. + + const reaction_rule_container_type& rrs(reaction_rules()); + for (reaction_rule_container_type::const_iterator i(rrs.begin()); + i != rrs.end(); ++i) + { + const ReactionRule::reactant_container_type& + reactants((*i).reactants()); + const ReactionRule::product_container_type& + products((*i).products()); + std::copy(reactants.begin(), reactants.end(), + std::back_inserter(retval)); + std::copy(products.begin(), products.end(), + std::back_inserter(retval)); + } + + std::sort(retval.begin(), retval.end()); + retval.erase( + std::unique(retval.begin(), retval.end()), retval.end()); + return retval; + } + + void add_species_attributes(const std::vector& attrs) + { + for (std::vector::const_iterator i(attrs.begin()); + i != attrs.end(); ++i) + { + add_species_attribute(*i); + } + } + + void add_species_attributes(const std::vector >& attrs) + { + for (std::vector >::const_iterator i(attrs.begin()); + i != attrs.end(); ++i) + { + add_species_attribute((*i).first, (*i).second); + } + } + + void add_species_attributes(const std::vector& attrs, const std::vector& proceeds) + { + if (attrs.size() != proceeds.size()) + { + throw IllegalArgument(""The size of lists must be the same.""); + } + + std::vector::const_iterator i(attrs.begin()); + std::vector::const_iterator j(proceeds.begin()); + for (; i != attrs.end() && j != proceeds.end(); ++i, ++j) + { + add_species_attribute(*i, *j); + } + } + + void add_reaction_rules(const std::vector& rrs) + { + for (std::vector::const_iterator i(rrs.begin()); + i != rrs.end(); ++i) + { + add_reaction_rule(*i); + } + } +}; + +} // ecell4 + +#endif /* ECELL4_MODEL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/UnitSpecies.hpp",".hpp","3903","183","#ifndef ECELL4_UNIT_SPECIES_HPP +#define ECELL4_UNIT_SPECIES_HPP + +#include +#include +#include + +#include + +#include ""types.hpp"" + +#include +#include +#include + + +namespace ecell4 +{ + +class UnitSpecies +{ +public: + + typedef std::string serial_type; + typedef std::pair site_type; + typedef std::vector > container_type; + +protected: + + typedef struct + { + typedef container_type::value_type value_type; + + bool operator()(const value_type& val1, const value_type& val2) + { + return val1.first < val2.first; + } + } site_comparerator; + +public: + + UnitSpecies(const std::string& name = """") + : name_(name) + { + ; + } + + std::string name() const + { + return name_; + } + + void set_name(const std::string& name) + { + name_ = name; + } + + void deserialize(const serial_type& serial); + + serial_type serial() const; + + void clear(); + + bool add_site(const std::string& name, + const std::string& state, const std::string& bond) + { + std::pair val( + std::make_pair(name, std::make_pair(state, bond))); + container_type::iterator it( + std::lower_bound(sites_.begin(), sites_.end(), val, site_comparerator())); + if (it == sites_.end() || (*it).first != name) + { + sites_.insert(it, val); + return true; + } + else + { + if (state != """") + { + (*it).second.first = state; + } + (*it).second.second = bond; + return false; + } + } + + Integer num_sites() const + { + return sites_.size(); + } + + bool has_site(const std::string& name) const + { + return std::binary_search(sites_.begin(), sites_.end(), + std::make_pair(name, site_type()), site_comparerator()); + } + + const site_type& get_site(const std::string& name) const + { + return (*std::lower_bound(sites_.begin(), sites_.end(), + std::make_pair(name, site_type()), site_comparerator())).second; + } + + inline container_type::const_iterator begin() const + { + return sites_.begin(); + } + + inline container_type::const_iterator end() const + { + return sites_.end(); + } + + //XXX: This method is not safe. Donot change the name of a site. + inline container_type::iterator begin() + { + return sites_.begin(); + } + + //XXX: This method is not safe. Donot change the name of a site. + inline container_type::iterator end() + { + return sites_.end(); + } + + bool operator==(const UnitSpecies& rhs) const + { + return (serial() == rhs.serial()); + } + + bool operator!=(const UnitSpecies& rhs) const + { + return (serial() != rhs.serial()); + } + + bool operator<(const UnitSpecies& rhs) const + { + return (serial() < rhs.serial()); + } + + bool operator>(const UnitSpecies& rhs) const + { + return (serial() > rhs.serial()); + } + + container_type::value_type& at(const container_type::size_type& idx) + { + return sites_.at(idx); + } + + container_type::value_type& at(const std::string& name) + { + return (*std::lower_bound(sites_.begin(), sites_.end(), + std::make_pair(name, site_type()), site_comparerator())); + } + + const container_type& sites() const + { + return sites_; + } + +protected: + + std::string name_; + container_type sites_; +}; + +} // ecell4 + +namespace std { +template<> +struct hash +{ + std::size_t operator()(const ecell4::UnitSpecies& val) const + { + return hash()(val.serial()); + } +}; +} // std + +#endif /* ECELL4_UNIT_SPECIES_HPP */ + +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/BDMLWriter.hpp",".hpp","12066","351","#ifndef ECELL4_BDML_WRITER_HPP +#define ECELL4_BDML_WRITER_HPP + +#include +#include +#include + +#include ""types.hpp"" +#include ""Species.hpp"" +#include ""Particle.hpp"" +#include ""WorldInterface.hpp"" +#include ""exceptions.hpp"" + +#ifdef WITH_HDF5 + +#include +#include + +namespace ecell4 +{ + +struct BDMLTraits +{ + typedef struct bdml_objectDef_struct { + uint32_t oID; + char name[128]; + } bdml_objectDef_struct; + + static H5::CompType get_bdml_objectDef_comp_type() + { + H5::CompType comp_type(sizeof(bdml_objectDef_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(comp_type.getId(), #member,\ + HOFFSET(bdml_objectDef_struct, member), type.getId()) + INSERT_MEMBER(oID, H5::PredType::STD_I32LE); + INSERT_MEMBER(name, H5::StrType(H5::PredType::C_S1, 128)); +#undef INSERT_MEMBER + return comp_type; + } + + typedef struct bdml_scaleUnit_struct { + char dimension[8]; + double xScale; + double yScale; + double zScale; + char sUnit[16]; + double tScale; + char tUnit[16]; + } bdml_scaleUnit_struct; + + static H5::CompType get_bdml_scaleUnit_comp_type() + { + H5::CompType comp_type(sizeof(bdml_scaleUnit_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(comp_type.getId(), #member,\ + HOFFSET(bdml_scaleUnit_struct, member), type.getId()) + INSERT_MEMBER(dimension, H5::StrType(H5::PredType::C_S1, 8)); + INSERT_MEMBER(xScale, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(yScale, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(zScale, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(sUnit, H5::StrType(H5::PredType::C_S1, 16)); + INSERT_MEMBER(tScale, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(tUnit, H5::StrType(H5::PredType::C_S1, 16)); +#undef INSERT_MEMBER + return comp_type; + } + + typedef struct bdml_sphere_struct { + char ID[16]; + double t; + char entity[8]; + double x; + double y; + double z; + double radius; + char label[16]; + } bdml_sphere_struct; + + static H5::CompType get_bdml_sphere_comp_type() + { + H5::CompType comp_type(sizeof(bdml_sphere_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(comp_type.getId(), #member,\ + HOFFSET(bdml_sphere_struct, member), type.getId()) + INSERT_MEMBER(ID, H5::StrType(H5::PredType::C_S1, 16)); + INSERT_MEMBER(t, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(entity, H5::StrType(H5::PredType::C_S1, 8)); + INSERT_MEMBER(x, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(y, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(z, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(radius, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(label, H5::StrType(H5::PredType::C_S1, 16)); +#undef INSERT_MEMBER + return comp_type; + } + + typedef struct bdml_point_struct { + char ID[16]; + double t; + char entity[8]; + double x; + double y; + double z; + char label[16]; + } bdml_point_struct; + + static H5::CompType get_bdml_point_comp_type() + { + H5::CompType comp_type(sizeof(bdml_point_struct)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(comp_type.getId(), #member,\ + HOFFSET(bdml_point_struct, member), type.getId()) + INSERT_MEMBER(ID, H5::StrType(H5::PredType::C_S1, 16)); + INSERT_MEMBER(t, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(entity, H5::StrType(H5::PredType::C_S1, 8)); + INSERT_MEMBER(x, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(y, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(z, H5::PredType::NATIVE_DOUBLE); + INSERT_MEMBER(label, H5::StrType(H5::PredType::C_S1, 16)); +#undef INSERT_MEMBER + return comp_type; + } +}; + +// template +void save_bd5( + const WorldInterface& world, const std::string& filename, + const int group_index, + const std::string& object_name, + const std::string& spatial_unit, + const std::string& time_unit, + const bool trunc, + const bool with_radius + ) +{ + //XXX: group_index = 0 + //XXX: object_name = ""molecule"" + //XXX: spatial_unit = ""meter"" + //XXX: time_unit = ""second"" + + typedef BDMLTraits traits_type; + + assert(group_index >= 0); + const std::string group_name + = static_cast(std::ostringstream() << std::dec << group_index).str(); + + H5E_auto2_t func; + void* client_data; + H5::Exception::getAutoPrint(func, &client_data); + + std::unique_ptr fout; + bool file_exists = false; + if (trunc) + { + std::unique_ptr tmp(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + fout.swap(tmp); + } + else + { + H5::Exception::dontPrint(); + try + { + std::unique_ptr tmp(new H5::H5File(filename.c_str(), H5F_ACC_RDWR)); + fout.swap(tmp); + H5::Exception::setAutoPrint(func, client_data); + file_exists = true; + } + catch (H5::FileIException &file_exists_err) + { + H5::Exception::setAutoPrint(func, client_data); + std::unique_ptr tmp(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + fout.swap(tmp); + } + } + + std::unique_ptr data; + + if (!file_exists) + { + std::unique_ptr + tmp(new H5::Group(fout->createGroup(""data""))); + data.swap(tmp); + + { + std::unique_ptr + objectDef_table(new traits_type::bdml_objectDef_struct[1]); + objectDef_table[0].oID = 0; + std::strcpy(objectDef_table[0].name, object_name.c_str()); + + const int RANK = 1; + hsize_t dim[] = {1}; + H5::DataSpace dataspace(RANK, dim); + std::unique_ptr objectDef( + new H5::DataSet(data->createDataSet(""objectDef"", traits_type::get_bdml_objectDef_comp_type(), dataspace))); + objectDef->write(objectDef_table.get(), objectDef->getDataType()); + } + + { + std::unique_ptr + scaleUnit_table(new traits_type::bdml_scaleUnit_struct[1]); + std::strcpy(scaleUnit_table[0].dimension, ""3D+T""); + scaleUnit_table[0].xScale = 1.0; + scaleUnit_table[0].yScale = 1.0; + scaleUnit_table[0].zScale = 1.0; + std::strcpy(scaleUnit_table[0].sUnit, spatial_unit.c_str()); + scaleUnit_table[0].tScale = 1.0; + std::strcpy(scaleUnit_table[0].tUnit, time_unit.c_str()); + + const int RANK = 1; + hsize_t dim[] = {1}; + H5::DataSpace dataspace(RANK, dim); + std::unique_ptr scaleUnit( + new H5::DataSet(data->createDataSet(""scaleUnit"", traits_type::get_bdml_scaleUnit_comp_type(), dataspace))); + scaleUnit->write(scaleUnit_table.get(), scaleUnit->getDataType()); + } + } + else + { + std::unique_ptr + tmp(new H5::Group(fout->openGroup(""data""))); + data.swap(tmp); + } + + H5::Exception::dontPrint(); + try + { + data->openGroup(group_name.c_str()); + H5::Exception::setAutoPrint(func, client_data); + std::stringstream ss; + ss << ""Group ["" << group_name << ""] already exists. Do nothing""; + throw AlreadyExists(ss.str()); + } + catch (H5::Exception &err) + { + H5::Exception::setAutoPrint(func, client_data); + + std::unique_ptr + data_zero(new H5::Group(data->createGroup(group_name.c_str()))); + std::unique_ptr + data_zero_object(new H5::Group(data_zero->createGroup(""object""))); + + typedef std::vector > + particle_container_type; + const particle_container_type particles(world.list_particles()); + // const particle_container_type& particles(world.list_particles()); + const unsigned int NUM_MOL = world.num_particles(); + + if (with_radius) + { + std::unique_ptr + data_table(new traits_type::bdml_sphere_struct[NUM_MOL]); + for (unsigned int i(0); i < NUM_MOL; ++i) + { + const ParticleID& pid(particles[i].first); + const Particle& p(particles[i].second); + + // std::strcpy(data_table[i].ID, ""1""); + std::strcpy(data_table[i].ID, + static_cast( + std::ostringstream() << std::dec << group_name << "":"" << i + << "":"" << pid.lot() << "":"" << pid.serial()).str().c_str()); + data_table[i].t = world.t(); + std::strcpy(data_table[i].entity, ""sphere""); + data_table[i].x = p.position()[0]; + data_table[i].y = p.position()[1]; + data_table[i].z = p.position()[2]; + data_table[i].radius = p.radius(); + std::strcpy(data_table[i].label, p.species().serial().c_str()); + } + + const int RANK = 1; + hsize_t dim[] = {NUM_MOL}; + H5::DataSpace dataspace(RANK, dim); + std::unique_ptr data_zero_object_zero( + new H5::DataSet(data_zero_object->createDataSet( + ""0"", traits_type::get_bdml_sphere_comp_type(), dataspace))); + data_zero_object_zero->write(data_table.get(), data_zero_object_zero->getDataType()); + } + else + { + std::unique_ptr + data_table(new traits_type::bdml_point_struct[NUM_MOL]); + for (unsigned int i(0); i < NUM_MOL; ++i) + { + const ParticleID& pid(particles[i].first); + const Particle& p(particles[i].second); + + // std::strcpy(data_table[i].ID, ""1""); + std::strcpy(data_table[i].ID, + static_cast( + std::ostringstream() << std::dec << group_name << "":"" << i + << "":"" << pid.lot() << "":"" << pid.serial()).str().c_str()); + data_table[i].t = world.t(); + std::strcpy(data_table[i].entity, ""point""); + data_table[i].x = p.position()[0]; + data_table[i].y = p.position()[1]; + data_table[i].z = p.position()[2]; + std::strcpy(data_table[i].label, p.species().serial().c_str()); + } + + const int RANK = 1; + hsize_t dim[] = {NUM_MOL}; + H5::DataSpace dataspace(RANK, dim); + std::unique_ptr data_zero_object_zero( + new H5::DataSet(data_zero_object->createDataSet( + ""0"", traits_type::get_bdml_point_comp_type(), dataspace))); + data_zero_object_zero->write(data_table.get(), data_zero_object_zero->getDataType()); + } + } +} + +}; // ecell4 + +#else // WITH_HDF5 + +namespace ecell4 +{ + +void save_bdml( + const WorldInterface& world, const std::string& filename, + const std::string& group_name, + const std::string& object_name, + const std::string& spatial_unit, + const std::string& time_unit, + const bool trunc + ) +{ + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +} + +void save_bd5( + const WorldInterface& world, const std::string& filename, + const int group_index, + const std::string& object_name, + const std::string& spatial_unit, + const std::string& time_unit, + const bool trunc, + const bool with_radius + ) +{ + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +} + +}; // ecell4 + +#endif // WITH_HDF5 + +#endif /* ECELL4_BDML_WRITER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/PeriodicRTree.hpp",".hpp","55218","1469","#ifndef ECELL4_CORE_PERIODIC_RTREE_HPP +#define ECELL4_CORE_PERIODIC_RTREE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +// AABBGetter should be a functor that calculate AABB from an instance of Object +// with the following interface. +// ``` +// struct AABBGetter { +// AABB operator()(const Object& obj, const Real margin) const noexcept; +// }; +// ``` +// Margin is used to reduce the cost of update. Removing and inserting an object +// costs high because it requires all the nodes on top of the leaf node to be +// adjusted. It sometimes causes node re-insertion. To avoid frequent update +// while the simulation that often causes fast oscillation of the object, the +// node AABB is expanded a bit and the margin buffers those small displacements. +// Essentially the value of the margin can be set any positive value. The size +// of the margin does not affect on the accuracy but only on the runtime +// efficiency. Thus AABBGetter can be implemented in several ways, e.g. +// 1. It can completely ignore the margin. +// 2. It can add constant offset to the box size. +// 3. It can combine object information and the margin. If a object has its +// diffusion coefficient `D`, the margin can be set as a factor of D. +// The only requirements for AABBGetter is that when margin == 0, the AABB +// should be exact (no margin). +// +// The default values of MinEntry and MaxEntry are not fine-tuned, so later +// we may need to tune it based on a benchmark result. +template +class PeriodicRTree +{ +public: + static_assert(!std::is_same::value, + ""Since node uses std::size_t as a internal node elements, "" + ""ObjectID should be distinguishable from std::size_t.""); + + using box_type = AABB; + using box_getter_type = AABBGetter; + using rtree_value_type = std::pair; + using value_type = std::pair; + using container_type = std::vector; + using iterator = typename container_type::iterator; + using const_iterator = typename container_type::const_iterator; + using key_to_value_map_type = std::unordered_map; + + static constexpr std::size_t min_entry = MinEntry; + static constexpr std::size_t max_entry = MaxEntry; + static constexpr std::size_t nil = std::numeric_limits::max(); + + struct node_type + { + using internal_entry_type = boost::container::static_vector; + using leaf_entry_type = boost::container::static_vector; + using entry_type = boost::variant; + + struct size_invoker: boost::static_visitor + { + template + std::size_t operator()(const T& v) const noexcept {return v.size();} + }; + + node_type(const internal_entry_type& inode, const std::size_t parent_, + const box_type& b) + : parent(parent_), entry(inode), box(b) + {} + node_type(const leaf_entry_type& leaf, const std::size_t parent_, + const box_type& b) + : parent(parent_), entry(leaf), box(b) + {} + ~node_type() = default; + node_type(node_type const&) = default; + node_type(node_type &&) = default; + node_type& operator=(node_type const&) = default; + node_type& operator=(node_type &&) = default; + + bool is_leaf() const noexcept {return entry.which() == 1;} + bool empty() const noexcept + { + return boost::apply_visitor(size_invoker(), this->entry) == 0; + } + bool has_enough_storage() const noexcept + { + return boost::apply_visitor(size_invoker(), this->entry) < max_entry; + } + bool has_enough_entry() const noexcept + { + return min_entry <= boost::apply_visitor(size_invoker(), this->entry); + } + + std::size_t size() const noexcept + { + return boost::apply_visitor(size_invoker(), this->entry); + } + + internal_entry_type const& inode_entry() const {return boost::get(entry);} + internal_entry_type& inode_entry() {return boost::get(entry);} + leaf_entry_type const& leaf_entry() const {return boost::get(entry);} + leaf_entry_type& leaf_entry() {return boost::get(entry);} + + std::size_t parent; + entry_type entry; + box_type box; + }; + + using internal_entry_type = typename node_type::internal_entry_type; + using leaf_entry_type = typename node_type::leaf_entry_type; + using tree_type = std::vector; + using index_buffer_type = std::vector; + +public: + + explicit PeriodicRTree(const Real3& edge_lengths, const Real margin = 0.0) + : root_(nil), margin_(margin), pbc_(edge_lengths) + { + // do nothing + } + ~PeriodicRTree() = default; + PeriodicRTree(PeriodicRTree const&) = default; + PeriodicRTree(PeriodicRTree &&) = default; + PeriodicRTree& operator=(PeriodicRTree const&) = default; + PeriodicRTree& operator=(PeriodicRTree &&) = default; + + std::size_t size() const noexcept + { + return this->container_.size(); + } + + bool empty() const noexcept {return this->root_ == nil;} + void clear() + { + this->root_ = nil; + this->tree_.clear(); + this->container_.clear(); + this->rmap_.clear(); + this->overwritable_nodes_.clear(); + return; + } + + bool has(const ObjectID& id) const + { + return rmap_.count(id) != 0; + } + value_type get(const ObjectID& id) const + { + assert(id == container_.at(rmap_.at(id)).first); + return container_.at(rmap_.at(id)); + } + + // collect values when the filter returns true. + // + // For example, see ParticleContainerRTreeImpl. + // ```cpp + // struct QueryFilter + // { + // // skip based on some attribute values in a value. + // // If it matches, you can put an additional information to the result. + // boost::optional + // operator()(const std::pair&, const Real3& edges); + // + // // to skip non-interacting nodes purely geometric criteria. + // bool operator()(const AABB&, const Real3& edges); + // } + // ``` + template + OutputIterator query(F matches, OutputIterator out) const + { + if(this->empty()) + { + return out; + } + return query_recursive(root_, matches, out); + } + + // update an object. If the object corresponds to id already exists, + // it reshapes the tree structure. + // + // When it reshape the structure, it considers the margin. If the node AABB + // covers the tight (i.e. margin == 0) object AABB, we don't need to reshape + // it. When the tight AABB of the object sticks out of the node AABB, we + // need to re-shape it. + bool update(const ObjectID& id, const Object& obj) + { + if(!this->has(id)) + { + this->insert(id, obj); + return true; + } + + const auto value_idx = this->rmap_.at(id); + const auto found = this->find_leaf(this->root_, + this->container_.at(value_idx)); + if(!found) + { + throw std::logic_error(""[error] internal error in PeriodicRTree""); + } + const auto node_idx = found->first; + assert(*(found->second) == id); + + const auto tight_box = this->box_getter_(obj, /*margin = */ 0.0); + const auto& node_box = this->node_at(node_idx).box; + + if(this->is_inside(tight_box, /* is inside of */ node_box)) + { + // the updated object is inside of the node AABB. + // We don't need to expand the box. just replace it. + this->container_.at(value_idx).second = obj; + } + else + { + // The updated object sticks out of the node. + // We need to expand the box and update the tree. + this->erase_impl(found->first, found->second); + this->insert(id, obj); + } + return false; + } + bool update(const value_type& v) + { + return this->update(v.first, v.second); + } + + void insert(const ObjectID& id, const Object& obj) + { + this->insert(std::make_pair(id, obj)); + } + void insert(const value_type& v) + { + this->add_value(v); + const auto box = this->box_getter_(v.second, this->margin_); + const auto L = this->choose_leaf(box); + assert(node_at(L).is_leaf()); + + if(node_at(L).has_enough_storage()) + { + if(node_at(L).empty()) + { + node_at(L).box = box; + } + else + { + node_at(L).box = this->expand(node_at(L).box, box); + } + this->node_at(L).leaf_entry().push_back(v.first); + this->adjust_tree(L); + assert(this->diagnosis()); + } + else // the most appropreate node is already full. split it. + { + const auto LL = this->add_node(this->split_leaf(L, v.first, box)); + assert(L != LL); + this->adjust_tree(L, LL); + assert(this->diagnosis()); + } + return ; + } + + void erase(const ObjectID& id) + { + this->erase(id, this->container_.at(this->rmap_.at(id))); + return; + } + void erase(const ObjectID& id, const Object& obj) + { + this->erase(std::make_pair(id, obj)); + return; + } + void erase(const value_type& v) + { + if(this->root_ == nil) + { + throw NotFound(""PeriodicRTree::erase: tree is empty.""); + } + + // find_leaf returns pair{leaf_node_idx, iterator of leaf_node.entry} + if(const auto found = this->find_leaf(this->root_, v)) + { + this->erase_impl(found->first, found->second); + assert(this->diagnosis()); + return; + } + + throw NotFound(""PeriodicRTree::erase: value not found.""); + } + + Real3 const& edge_lengths() const noexcept {return pbc_.edge_lengths();} + void reset_boundary(const Real3& edges) noexcept {return pbc_.reset(edges);} + + // user-defined AABBGetter may be stateful (unlikely). + AABBGetter const& get_aabb_getter() const noexcept {return box_getter_;} + + // box margin. + Real margin() const noexcept {return margin_;} + + // container = std::vector>. + container_type const& list_objects() const {return container_;} + + value_type const& at(const ObjectID& id) const + { + assert(id == container_.at(rmap_.at(id)).first); + return container_.at(rmap_.at(id)); + } + // Unsafe. If an object of a shape is modified via this function, + // RTree cannot notice that. In such a case, the consistency in the geometry + // would be broken. DON'T MODIFY THE SHAPE through the reference. + value_type& at(const ObjectID& id) + { + assert(id == container_.at(rmap_.at(id)).first); + return container_.at(rmap_.at(id)); + } + + value_type& front() noexcept {return this->container_.front();} + value_type const& front() const noexcept {return this->container_.front();} + + value_type& back() noexcept {return this->container_.back();} + value_type const& back() const noexcept {return this->container_.back();} + + iterator begin() noexcept {return this->container_.begin();} + iterator end() noexcept {return this->container_.end();} + const_iterator begin() const noexcept {return this->container_.begin();} + const_iterator end() const noexcept {return this->container_.end();} + const_iterator cbegin() const noexcept {return this->container_.cbegin();} + const_iterator cend() const noexcept {return this->container_.cend();} + + // check the tree structure and relationships between nodes + bool diagnosis() const + { + // ------------------------------------------------------------------- + // check number of active internal nodes + std::size_t num_inodes = 1; // +1 for the root + for(std::size_t i=0; iis_valid_node_index(i)){continue;} + + if(!this->node_at(i).is_leaf()) + { + num_inodes += this->node_at(i).inode_entry().size(); + } + } + if(tree_.size() - overwritable_nodes_.size() != num_inodes) + { + std::cerr << ""tree_.size() is not consistent with number of "" + ""internal nodes"" << std::endl; + return false; + } + + // ------------------------------------------------------------------- + // check the parent of a node exists and the parent contains the node + bool root_found = false; + for(std::size_t i=0; iis_valid_node_index(i)){continue;} + + if(this->node_at(i).parent == nil) + { + assert(!root_found); + root_found = true; + } + else + { + const auto& e = this->node_at(this->node_at(i).parent).inode_entry(); + assert(this->is_valid_node_index(this->node_at(i).parent)); + assert(!this->node_at(this->node_at(i).parent).is_leaf()); + assert(std::find(e.begin(), e.end(), i) != e.end()); + } + } + + // ------------------------------------------------------------------- + // check all the centroid of all the node AABBs are within the boundary + for(std::size_t i=0; iis_valid_node_index(i)){continue;} + + const auto& box = this->node_at(i).box; + const auto center = (box.upper() + box.lower()) * 0.5; + if(!is_inside_of_boundary(center)) + { + std::cerr << ""box: "" << box.lower() << "":"" << box.upper() << std::endl; + std::cerr << ""center: "" << center << std::endl; + } + assert(this->is_inside_of_boundary(center)); + } + + // ------------------------------------------------------------------- + // check all the ancester node AABBs covers the child AABBs + for(std::size_t i=0; iis_valid_node_index(i)) {continue;} + if(!node_at(i).is_leaf()) {continue;} + + if(!diagnosis_rec(i)) + { + std::cerr << ""node "" << i << "" is not covered by its ancestors"" + << std::endl; + this->dump_from_leaf_to_root(i, std::cerr); + this->dump(std::cerr); + return false; + } + } + + // ------------------------------------------------------------------- + // check consistency between id->index map and the tree + for(std::size_t i=0; ifind_leaf(this->root_, container_.at(i))) + { + std::cerr << ""Object "" << container_.at(i).first << "":"" + << container_.at(i).second << "" is not found in the "" + << ""tree"" << std::endl; + return false; + } + } + return true; + } + + // ------------------------------------------------------------------- + // dump parent-child relationship + void dump(std::ostream& os) const + { + std::ostringstream oss; + if(this->is_valid_node_index(this->root_)) {oss << ' ';} else {oss << '!';} + oss << '(' << std::setw(3) << this->root_ << "") ""; + this->dump_rec(this->root_, os, oss.str()); + os << std::flush; + return ; + } + +private: + + // ------------------------------------------------------------------- + // check all the ancester node AABBs covers the child AABBs recursively + bool diagnosis_rec(std::size_t node_idx) const + { + while(node_at(node_idx).parent != nil) + { + const auto& node = this->node_at(node_idx); + if(!(this->is_inside(node.box, node_at(node.parent).box))) + { + std::cerr << ""parent AABB: "" << node_at(node.parent).box.lower() + << "" -> "" << node_at(node.parent).box.upper() + << std::endl; + std::cerr << ""current AABB: "" << node.box.lower() + << "" -> "" << node.box.upper() + << std::endl; + return false; + } + node_idx = node.parent; + } + return true; + } + + // ------------------------------------------------------------------- + // dump parent-child relationship + void dump_rec(const std::size_t node_idx, std::ostream& os, std::string prefix) const + { + const auto& node = tree_.at(node_idx); + if(node.is_leaf()) + { + for(const auto& entry_id : node.leaf_entry()) + { + os << prefix; + os << '[' << std::setw(3) << entry_id << ""]\n""; + } + return; + } + else + { + for(const std::size_t entry : node.inode_entry()) + { + std::ostringstream oss; + if(!this->is_valid_node_index(entry)){oss << '!';} else {oss << ' ';} + oss << '(' << std::setw(3) << entry << "") ""; + dump_rec(entry, os, prefix + oss.str()); + } + } + return; + } + + void dump_from_leaf_to_root(std::size_t node_idx, std::ostream& os) const + { + std::ostringstream relation; + std::ostringstream boxes; + do + { + relation << node_idx; + const auto& node = this->node_at(node_idx); + if(node.parent != nil) {relation << "" -> "";} + + boxes << node.box.lower() << "":"" << node.box.upper() << '\n'; + node_idx = node.parent; + } + while(this->node_at(node_idx).parent != nil); + os << relation.str() << std::endl; + os << boxes.str() << std::endl; + return; + } + +private: + + // ------------------------------------------------------------------------ + // recursively search nodes. if the node is a leaf, check values inside it. + + template + OutputIterator query_recursive(const std::size_t node_idx, + const F& matches, OutputIterator& out) const + { + const node_type& node = this->node_at(node_idx); + if(node.is_leaf()) + { + for(const auto& entry : node.leaf_entry()) + { + const auto& value = container_.at(rmap_.at(entry)); + if(const auto info = matches(value, this->pbc_)) + { + *out = *info; + ++out; + } + } + return out; + } + // internal node. search recursively... + for(const std::size_t entry : node.inode_entry()) + { + const auto& node_aabb = node_at(entry).box; + if(matches(node_aabb, this->pbc_)) + { + this->query_recursive(entry, matches, out); + } + } + return out; + } + +private: + + // ------------------------------------------------------------------------ + // get node. In the debug mode (w/o -DNDEBUG), it checks the requrested node + // is available. + + node_type& node_at(const std::size_t i) + { + assert(this->is_valid_node_index(i)); + return tree_.at(i); + } + node_type const& node_at(const std::size_t i) const + { + assert(this->is_valid_node_index(i)); + return tree_.at(i); + } + + + void erase_impl(const std::size_t node_idx, + const typename node_type::leaf_entry_type::const_iterator value_iter) + { + const auto value_id = *value_iter; + this->node_at(node_idx).leaf_entry().erase(value_iter); + this->erase_value(rmap_.at(value_id)); + + this->condense_box(node_idx); + this->condense_leaf(node_idx); + return; + } + + // ======================================================================== + // below: construct and manage RTree structure. + + // It choose leaf object to contain the entry. It is an implementation of + // the quadratic algorithm introduced in the paper by Guttman A. (1984) + std::size_t choose_leaf(const box_type& entry) + { + // if it's empty, the entry will be inserted in a root node. + if(this->root_ == nil) + { + node_type n(leaf_entry_type{/*empty*/}, /*parent = */ nil, entry); + this->root_ = this->add_node(n); + return this->root_; + } + + // choose a leaf where entry will be inserted. + // + // search node that can contain the new entry with minimum expansion + // until it found a leaf. + std::size_t node_idx = this->root_; + while(!(this->node_at(node_idx).is_leaf())) + { + // find the node that can cover the entry with minimum expansion + Real diff_area_min = std::numeric_limits::max(); + Real area_min = std::numeric_limits::max(); + + // look all the child nodes and find the node that can contain the + // new entry with minimum expansion + const auto& node = this->node_at(node_idx); + for(const std::size_t i : node.inode_entry()) + { + const auto& current_box = this->node_at(i).box; + + const Real area_initial = this->area(current_box); + const Real area_expanded = this->area(this->expand(current_box, entry)); + + const Real diff_area = area_expanded - area_initial; + if((diff_area < diff_area_min) || + (diff_area == diff_area_min && area_expanded < area_min)) + { + node_idx = i; + diff_area_min = diff_area; + area_min = std::min(area_min, area_expanded); + } + } + } + return node_idx; + } + + void adjust_tree(std::size_t node_idx) + { + while(this->node_at(node_idx).parent != nil) + { + const auto& node = this->node_at(node_idx); + auto& parent = this->node_at(node.parent); + + // if node.box is already inside of parent.box, then we don't need + // to expand node AABBs. + if(this->is_inside(node.box, parent.box, 0.0)) + { + break; + } + parent.box = this->expand(parent.box, node.box); + node_idx = node.parent; + } + return; + } + + // It adjusts node AABBs and add a new node to proper location. + void adjust_tree(const std::size_t N, const std::size_t NN) + { + assert(N != NN); + + // we hit the root. to assign a new node, we need to make tree deeper. + if(this->node_at(N).parent == nil) + { + node_type new_root(internal_entry_type{N, NN}, /*parent = */ nil, + this->expand(node_at(N).box, node_at(NN).box)); + this->root_ = this->add_node(std::move(new_root)); + + this->node_at( N).parent = this->root_; + this->node_at(NN).parent = this->root_; + return; + } + else + { + const auto& node = this->node_at(N); + const auto& partner = this->node_at(NN); + assert(node.parent == partner.parent); + assert(!node_at(node.parent).is_leaf()); + + const auto parent_idx = node.parent; + auto& parent = this->node_at(parent_idx); + parent.box = this->expand(parent.box, node.box); + + if(parent.has_enough_storage()) + { + parent.box = this->expand(parent.box, partner.box); // assign NN + parent.inode_entry().push_back(NN); + + // NN is assigned to this node. + // expand AABBs of parent nodes if needed. + return this->adjust_tree(parent_idx); + } + else + { + // NN cannot be assigned to this node. + // split node and rearrange the tree. + // + // parent -+- N }- MaxEntry + // +- ... } + // +- (NN) + // + // | + // v + // + // -+-parent -+- N }- less than MaxEntry + // | +- ... } + // | + // +-PP -+- ... }- less than MaxEntry + // +- NN } + // + const auto PP = this->split_node(parent_idx, NN); + assert(parent_idx != PP); + return this->adjust_tree(parent_idx, PP); + } + } + } + + // split internal nodes by the quadratic algorithm introduced by Guttman, A. (1984) + std::size_t split_node(const std::size_t P, const std::size_t NN) + { + // P -+- N }- MaxEntry + // +- ... } + // +- (NN) + // + // | split into + // v + // + // -+-P -+- N + // | +- ... + // | + // +-PP -+- ... + // +- NN + + const std::size_t PP = this->add_node( + node_type(internal_entry_type{}, node_at(P).parent, box_type())); + + assert(P != PP); + assert(NN != PP); + + node_type& node = this->node_at(P); + node_type& partner = this->node_at(PP); + // these are internal nodes. + assert(!node.is_leaf()); + assert(!partner.is_leaf()); + + boost::container::static_vector< + std::pair, max_entry + 1> entries; + entries.emplace_back(NN, node_at(NN).box); + + for(const auto& entry_idx : node.inode_entry()) + { + entries.emplace_back(entry_idx, this->node_at(entry_idx).box); + } + node .inode_entry().clear(); + partner.inode_entry().clear(); + + // assign first 2 entries to node and partner + { + const auto seeds = this->pick_seeds(entries); + assert(seeds[0] != seeds[1]); + + node .inode_entry().push_back(entries.at(seeds[0]).first); + partner.inode_entry().push_back(entries.at(seeds[1]).first); + + this->node_at(entries.at(seeds[0]).first).parent = P; + this->node_at(entries.at(seeds[1]).first).parent = PP; + + node .box = entries.at(seeds[0]).second; + partner.box = entries.at(seeds[1]).second; + + // Remove them from entries pool. the order should be kept. + // + // Remove the one corresponds to the larger index first. Otherwise, + // after removing one, index of the other one would be changed. + entries.erase(entries.begin() + std::max(seeds[0], seeds[1])); + entries.erase(entries.begin() + std::min(seeds[0], seeds[1])); + } + + while(!entries.empty()) + { + // If we need all the rest of entries to achieve min_entry, + // use all of them. + if(min_entry > node.size() && + min_entry - node.size() >= entries.size()) + { + for(const auto idx_box : entries) + { + this->node_at(idx_box.first).parent = P; + node.inode_entry().push_back(idx_box.first); + node.box = this->expand(node.box, idx_box.second); + } + return PP; + } + if(min_entry > partner.size() && + min_entry - partner.size() >= entries.size()) + { + for(const auto idx_box : entries) + { + this->node_at(idx_box.first).parent = PP; + partner.inode_entry().push_back(idx_box.first); + partner.box = this->expand(partner.box, idx_box.second); + } + return PP; + } + + // choose which entry will be assigned to which node + const auto next = this->pick_next(entries, node.box, partner.box); + if(next.second) + { + node.inode_entry().push_back(entries.at(next.first).first); + this->node_at(entries.at(next.first).first).parent = P; + node.box = this->expand(node.box, entries.at(next.first).second); + } + else + { + partner.inode_entry().push_back(entries.at(next.first).first); + this->node_at(entries.at(next.first).first).parent = PP; + partner.box = this->expand(partner.box, entries.at(next.first).second); + } + entries.erase(entries.begin() + next.first); + } + this->node_at(P) = node; + this->node_at(PP) = partner; + return PP; + } + + // split leaf nodes by the quadratic algorithm introduced by Guttman, A. (1984) + node_type split_leaf(const std::size_t N, const ObjectID& vid, + const box_type& entry) + { + node_type& node = node_at(N); + node_type partner(leaf_entry_type{}, node.parent, box_type()); + assert(node.is_leaf()); + + boost::container::static_vector< + std::pair, max_entry + 1> entries; + entries.push_back(std::make_pair(vid, entry)); + + for(const auto& entry_id : node.leaf_entry()) + { + entries.emplace_back(entry_id, + box_getter_(container_.at(rmap_.at(entry_id)).second, margin_)); + } + + node .leaf_entry().clear(); + partner.leaf_entry().clear(); + + // assign first 2 entries to node and partner + { + const auto seeds = this->pick_seeds(entries); + node .leaf_entry().push_back(entries.at(seeds[0]).first); + partner.leaf_entry().push_back(entries.at(seeds[1]).first); + + node .box = entries.at(seeds[0]).second; + partner.box = entries.at(seeds[1]).second; + + // remove them from entries pool + // + // Remove the one corresponds to the larger index first. Otherwise, + // after removing one, index of the other one would be changed. + entries.erase(entries.begin() + std::max(seeds[0], seeds[1])); + entries.erase(entries.begin() + std::min(seeds[0], seeds[1])); + } + + while(!entries.empty()) + { + if(min_entry > node.size() && + min_entry - node.size() >= entries.size()) + { + for(const auto& idx_box : entries) + { + node.leaf_entry().push_back(idx_box.first); + node.box = this->expand(node.box, idx_box.second); + } + return partner; + } + if(min_entry > partner.size() && + min_entry - partner.size() >= entries.size()) + { + for(const auto& idx_box : entries) + { + partner.leaf_entry().push_back(idx_box.first); + partner.box = this->expand(partner.box, idx_box.second); + } + return partner; + } + + const auto next = this->pick_next(entries, node.box, partner.box); + if(next.second) // next is for node + { + node.leaf_entry().push_back(entries.at(next.first).first); + node.box = this->expand(node.box, entries.at(next.first).second); + } + else // next is for partner + { + partner.leaf_entry().push_back(entries.at(next.first).first); + partner.box = this->expand(partner.box, entries.at(next.first).second); + } + entries.erase(entries.begin() + next.first); + } + return partner; + } + + // auxiliary function for the quadratic algorithm. + template + std::array + pick_seeds(const boost::container::static_vector< + std::pair, max_entry+1>& entries) const + { + assert(entries.size() >= 2); + + std::array retval{{ + std::numeric_limits::max(), + std::numeric_limits::max() + }}; + + boost::container::static_vector areas; + for(const auto& idx_box : entries) + { + areas.push_back(this->area(idx_box.second)); + } + + // Choose a pair that are most distant to each other. + // When we split a node, we always start such a pair. + Real max_d = -std::numeric_limits::max(); + for(std::size_t i=0; i+1expand(ibox, jbox); + const Real d = this->area(merged) - iarea - areas.at(j); + if(max_d < d) + { + max_d = d; + retval[0] = i; + retval[1] = j; + } + } + } + return retval; + } + + // auxiliary function for the quadratic algorithm. + template + std::pair + pick_next(const boost::container::static_vector< + std::pair, max_entry+1>& entries, + const box_type& node, const box_type& ptnr) const + { + assert(!entries.empty()); + + bool is_node; + Real max_dd = -1; + std::size_t idx; + for(std::size_t i=0; iexpand(node, idx_box.second); + const auto box2 = this->expand(ptnr, idx_box.second); + + const Real d1 = this->area(box1) - this->area(node); + const Real d2 = this->area(box2) - this->area(ptnr); + const Real dd = d1 - d2; + if(max_dd < std::abs(dd)) + { + max_dd = std::abs(dd); + idx = i; + is_node = (dd < 0); + } + } + return std::make_pair(idx, is_node); + } + + + // find leaf node that contains the entry value in a recursive manner. + // + // returns pairof{leaf-node-index, entry-index-in-node} + boost::optional> + find_leaf(std::size_t node_idx, const value_type& entry) const + { + const node_type& node = this->node_at(node_idx); + const auto tight_box = this->box_getter_(entry.second, 0.0); + + if(!(this->is_inside(tight_box, node.box))) + { + return boost::none; + } + if(node.is_leaf()) + { + for(auto i=node.leaf_entry().begin(), e=node.leaf_entry().end(); i!=e; ++i) + { + // if the ID is the same, then the objects should be the same. + if(container_.at(rmap_.at(*i)).first == entry.first) + { + return std::make_pair(node_idx, i); + } + } + return boost::none; + } + else // node is an internal node + { + for(auto i=node.inode_entry().begin(), e=node.inode_entry().end(); i!=e; ++i) + { + if(!(this->is_inside(tight_box, this->node_at(*i).box))) + { + continue; + } + if(const auto found = this->find_leaf(*i, entry)) + { + return found; + } + } + return boost::none; + } + } + + // check the number of entries in the Nth leaf node. If it has too few + // entries, it removes the node and balance the tree. + void condense_leaf(const std::size_t N) + { + const node_type& node = this->node_at(N); + assert(node.is_leaf()); + + if(node.has_enough_entry() || node.parent == nil) + { + return; // nothing is needed. + } + + // Leaf has too few entries. The tree structure should be balanced. + // Here, the naivest approach is chosen. First remove the leaf node + // that has too few children and re-insert all of them later. + + // copy objects in the leaf node that is being removed to re-insert them later + std::vector eliminated_objs; + eliminated_objs.reserve(node.size()); + for(const auto& id: node.leaf_entry()) + { + const std::size_t idx = rmap_.at(id); + eliminated_objs.push_back(this->container_.at(idx)); + this->erase_value(idx); + } + + const auto parent_idx = node.parent; + + // erase the node N from its parent and condense aabb + auto found = std::find(this->node_at(node.parent).inode_entry().begin(), + this->node_at(node.parent).inode_entry().end(), N); + assert(found != this->node_at(node.parent).inode_entry().end()); + + this->erase_node(*found); + this->node_at(parent_idx).inode_entry().erase(found); + + // condense node parent box without the leaf node N. + this->condense_box(parent_idx); + + this->condense_node(parent_idx); + + // re-insert entries that were in node N + for(const auto& obj : eliminated_objs) + { + this->insert(obj); + } + return; + } + + // check the number of entries in the Nth internal node. If it has too few + // entries, it removes the node and balance the tree. + void condense_node(const std::size_t N) + { + const node_type& node = this->node_at(N); + assert(!node.is_leaf()); + + if(node.has_enough_entry()) + { + return; // if the node has enough number of entries, then it's okay. + } + if(node.parent == nil) + { + if(node.size() == 1) + { + // if the root has only one entry, then the child node of the + // current root node should be the root node. + this->root_ = node.inode_entry().front(); + this->erase_node(N); + assert(!this->is_valid_node_index(N)); + return; + } + // if we hit the root, then everything is done. + // Note that here we don't have enough number of entries in the + // root node. We can further optimize the tree structure but it + // is a hard and time-consuming task. Here we just keep the tree. + return ; + } + + // collect index of nodes that are children of the node to be removed + const std::vector eliminated_nodes( + node.inode_entry().begin(), node.inode_entry().end()); + const auto parent_idx = node.parent; + + // erase the node N from its parent and condense its aabb + auto found = std::find(this->node_at(parent_idx).inode_entry().begin(), + this->node_at(parent_idx).inode_entry().end(), N); + assert(found != this->node_at(parent_idx).inode_entry().end()); + + // remove the node from its parent.entry + this->erase_node(*found); + this->node_at(parent_idx).inode_entry().erase(found); + this->condense_box(parent_idx); + + // re-insert nodes eliminated from node N + for(const auto& idx : eliminated_nodes) + { + this->re_insert(idx); + } + this->condense_node(parent_idx); + return; + } + + // re-calculate the AABB of a node to make sure that the node covers all the + // child nodes. + // + // Note: In the original R-Tree, i.e. without periodic boundary condition, + // we don't need to adjust tree after we remove an object. It is + // because node AABB always shrink after erasing its entry. But under + // the periodic condition, AABB may slide to reduce its size. + // Let's consider the following case. When we remove the 3rd + // object, the node AABB slides to the left side. By removing the + // object, the region that was not covered by the node AABB, between + // object 1 and 2, will be covered. + // + // .--------- boundary --------. .--------- boundary --------. + // : _____ _ ___ _ : => : _____ _ _ : + // : | 1 | |2| | 3 | |4|: => : | 1 | |2| |4|: + // : |_____| |_| |___| |_|: => : |_____| |_| |_|: + // --------] [--node AABB--- => --node AABB-----] [--- + // + // We need to choose a strategy to handle this problem. There can + // be several possible ways. First, we can keep the original AABB + // after removing an object. Apparently, since the older AABB covers + // all the child objects, we can keep the AABB. But it enlarges AABB + // and makes the whole R-Tree inefficient. Second, we can adjust all + // the ancester nodes. It might also causes inefficiency because it + // requires additional calculation when erasing an object. But it make + // node AABB smaller and the total efficiency can increase compared to + // the former solution. + void condense_box(const std::size_t N) + { + node_type& node = this->node_at(N); + if(node.empty()) + { + // If the entry is empty, the node will soon be eliminated from its + // parent node via `condense_leaf` or `condense_node`. + // We can delete this operation and just return from this method, + // but I'm not completely sure yet. + const auto center = (node.box.upper() + node.box.lower()) * 0.5; + node.box = box_type(center, center); + return; + } + if(node.is_leaf()) + { + const auto& entries = node.leaf_entry(); + node.box = box_getter_( + this->container_.at(rmap_.at(entries.front())).second, margin_); + for(auto i = std::next(entries.begin()); i != entries.end(); ++i) + { + node.box = this->expand(node.box, + box_getter_(container_.at(rmap_.at(*i)).second, margin_)); + } + } + else + { + const auto& entries = node.inode_entry(); + node.box = this->node_at(entries.front()).box; + for(auto i = std::next(entries.begin()); i != entries.end(); ++i) + { + node.box = this->expand(node.box, this->node_at(*i).box); + } + } + + // XXX Note: read the comments on top of this function carefully. + this->adjust_tree(N); + return; + } + + // re-insert nodes that are temporary removed from its (previous) parent + // node to balance the number of nodes. This will only be called from + // `condense_node`. + void re_insert(const std::size_t N) + { + // reset connection to the parent! + + // insert node to its proper parent. to find the parent of this node N, + // add 1 to level. root node should NOT come here. + const std::size_t level = this->level_of(N) + 1; + const box_type& entry = this->node_at(N).box; + const std::size_t L = this->choose_node_with_level(entry, level); + assert(!this->node_at(L).is_leaf()); + + if(node_at(L).has_enough_storage()) + { + node_at(L).inode_entry().push_back(N); + node_at(N).parent = L; + node_at(L).box = this->expand(this->node_at(L).box, entry); + this->adjust_tree(L); + } + else + { + const std::size_t LL = this->split_node(L, N); + this->adjust_tree(L, LL); + } + return; + } + + // choose where the node should be inserted by using the box size and + // the level of the node. + std::size_t + choose_node_with_level(const box_type& entry, const std::size_t level) + { + std::size_t node_idx = this->root_; + if(this->level_of(node_idx) < level) + { + throw std::logic_error(""PeriodicRTree: No such a high level node.""); + } + + while(this->level_of(node_idx) != level) + { + Real diff_area_min = std::numeric_limits::max(); + Real area_min = std::numeric_limits::max(); + + const node_type& node = this->node_at(node_idx); + for(const auto& entry_idx : node.inode_entry()) + { + const auto& entry_box = node_at(entry_idx).box; + const Real area_initial = this->area(entry_box); + const box_type box = this->expand(entry_box, entry); + + const Real area_expanded = this->area(box); + const Real diff_area = area_expanded - area_initial; + if(diff_area < diff_area_min || + (diff_area == diff_area_min && area_expanded < area_min)) + { + node_idx = entry_idx; + diff_area_min = diff_area; + area_min = std::min(area_expanded, area_min); + } + } + } + return node_idx; + } + + // the naivest approach; going down until it hits leaf. + // If the node is a leaf, level == 0. + std::size_t level_of(std::size_t node_idx) const + { + std::size_t level = 0; + while(!(node_at(node_idx).is_leaf())) + { + ++level; + node_idx = node_at(node_idx).inode_entry().front(); + } + return level; + } + +private: + + // ======================================================================== + // utility member methods to handle `container_` and `tree_`. + + // ------------------------------------------------------------------------ + // for nodes + // + // RTree stores nodes by their index in a container, `tree_`. + // Thus the indices should be kept when we insert a new node or remove an + // old node. + + // re-use overwritable region if it exists. + std::size_t add_node(const node_type& n) + { + if(overwritable_nodes_.empty()) + { + const std::size_t new_index = tree_.size(); + tree_.push_back(n); + return new_index; + } + const std::size_t new_index = overwritable_nodes_.back(); + overwritable_nodes_.pop_back(); + node_at(new_index) = n; + return new_index; + } + // mark index `i` overritable and fill old value by the default value. + void erase_node(const std::size_t i) + { + node_at(i) = node_type(internal_entry_type{}, nil, box_type()); + overwritable_nodes_.push_back(i); + assert(!this->is_valid_node_index(i)); + return; + } + bool is_valid_node_index(const std::size_t i) const noexcept + { + return std::find(overwritable_nodes_.begin(), + overwritable_nodes_.end(), i) == + overwritable_nodes_.end(); + } + + // ------------------------------------------------------------------------ + // for values + + std::size_t add_value(const value_type& v) + { + const std::size_t new_index = container_.size(); + container_.push_back(v); + rmap_[v.first] = new_index; + return new_index; + } + void erase_value(const std::size_t i) + { + using std::swap; + swap(container_.at(i), container_.back()); + + assert(rmap_.at(container_.at(i).first) == container_.size() - 1); + rmap_[container_.at(i).first] = i; + + const auto status = rmap_.erase(container_.back().first); + assert(status == 1); + (void)status; + + container_.pop_back(); + return ; + } + +private: + + // ------------------------------------------------------------------------ + // geometric methods to modify AABB under periodic boundary condition. + + // upper/lower of AABB are not adjusted to the PBC but the center is aligned. + // so the width is always correct. + Real area(const box_type& box) const noexcept + { + const auto dx = box.upper() - box.lower(); + return dx[0] * dx[1] * dx[2]; + } + + // merge two AABBs under the PBC. + // + // It is guaranteed that the resulting AABB contains both lhs and rhs. + box_type expand(const box_type& lhs, const box_type& rhs) const noexcept + { + // assuming that upper/lower can stick out of the boundary + const auto lc = (lhs.upper() + lhs.lower()) * 0.5; // center of lhs + const auto rc = (rhs.upper() + rhs.lower()) * 0.5; // center of rhs + const auto rr = rhs.upper() - rc; // radius of rhs + const auto dc = restrict_direction(rc - lc); // distance between centers + const auto l1 = lhs.lower(); + const auto u1 = lhs.upper(); + const auto l2 = lc + dc - rr; // boundary-adjusted rhs' lower bound + const auto u2 = lc + dc + rr; // ditto + + Real3 up, lw; + for(std::size_t i=0; i<3; ++i) + { + lw[i] = std::min(l1[i], l2[i]); + up[i] = std::max(u1[i], u2[i]); + } + const auto c = (up + lw) * 0.5; + const auto d = restrict_position(c) - c; + + box_type expanded(lw + d, up + d); + + assert(is_inside(lhs, expanded, 1e-8)); + assert(is_inside(rhs, expanded, 1e-8)); + + return expanded; + } + + // check if two AABBs intersects each other, under the PBC. + bool intersects(const box_type& lhs, const box_type& rhs, + const Real tol = 1e-8) const noexcept + { + const auto lc = (lhs.upper() + lhs.lower()) * 0.5; // center of lhs + const auto lr = (lhs.upper() - lhs.lower()) * 0.5; // radius of lhs + const auto rc = (rhs.upper() + rhs.lower()) * 0.5; // center of rhs + const auto rr = (rhs.upper() - rhs.lower()) * 0.5; // radius of rhs + + const auto r2 = lr + rr; + const auto dc = ecell4::abs(this->restrict_direction(lc - rc)); + + // if they are close along all the axes, they intersects each other. + return ((dc[0] - r2[0]) <= tol) && + ((dc[1] - r2[1]) <= tol) && + ((dc[2] - r2[2]) <= tol); + } + + // if lhs is inside of rhs, return true. + bool is_inside(const box_type& lhs, const box_type& rhs, + const Real tol = 1e-8) const noexcept + { + const auto lc = (lhs.upper() + lhs.lower()) * 0.5; // center of lhs + const auto lr = (lhs.upper() - lhs.lower()) * 0.5; // radius of lhs + const auto rc = (rhs.upper() + rhs.lower()) * 0.5; // center of rhs + const auto rr = (rhs.upper() - rhs.lower()) * 0.5; // radius of rhs + + const auto dr = rr - lr; // radius difference + const auto dc = abs(this->restrict_direction(lc - rc)); // distance between centers + + // if the radius (of the right hand side) is larger than the half width, + // that means that the right hand side wraps the whole world. + const auto& edges = pbc_.edge_lengths(); + return ((dc[0] - dr[0]) <= tol || (edges[0] * 0.5 <= rr[0])) && + ((dc[1] - dr[1]) <= tol || (edges[1] * 0.5 <= rr[1])) && + ((dc[2] - dr[2]) <= tol || (edges[2] * 0.5 <= rr[2])); + } + + bool is_inside_of_boundary(const Real3 r, const Real tol = 1e-8) const noexcept + { + const auto& edges = pbc_.edge_lengths(); + const auto rel_tol = edges * tol; + if(r[0] < -rel_tol[0] || edges[0] + rel_tol[0] < r[0]) {return false;} + if(r[1] < -rel_tol[1] || edges[1] + rel_tol[1] < r[1]) {return false;} + if(r[2] < -rel_tol[2] || edges[2] + rel_tol[2] < r[2]) {return false;} + return true; + } + + Real3 restrict_position(Real3 r) const noexcept + { + return pbc_.apply_boundary(r); + } + Real3 restrict_direction(Real3 dr) const noexcept + { + // Assuming that ... + // - dr = r1 - r2 + // - Both r1 and r2 are inside of the boundary. + const auto edges = pbc_.edge_lengths(); + const auto halfw = edges * 0.5; + if ( dr[0] < -halfw[0]) {dr[0] += edges[0];} + else if(halfw[0] <= dr[0]) {dr[0] -= edges[0];} + if ( dr[1] < -halfw[1]) {dr[1] += edges[1];} + else if(halfw[1] <= dr[1]) {dr[1] -= edges[1];} + if ( dr[2] < -halfw[2]) {dr[2] += edges[2];} + else if(halfw[2] <= dr[2]) {dr[2] -= edges[2];} + return dr; + } + +private: + + std::size_t root_; // index of the root node. + Real margin_; // margin of the Box. + PeriodicBoundary pbc_; // boundary condition. + tree_type tree_; // vector of nodes. + container_type container_; // vector of Objects. + key_to_value_map_type rmap_; // map from ObjectID to index + index_buffer_type overwritable_nodes_; // list ""already-removed"" nodes + box_getter_type box_getter_; // AABBGetter can be stateful. +}; + +template +constexpr std::size_t PeriodicRTree::nil; +template +constexpr std::size_t PeriodicRTree::min_entry; +template +constexpr std::size_t PeriodicRTree::max_entry; + +} // ecell4 +#endif// ECELL4_PERIODIC_RTREE_IMPL_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Circle.hpp",".hpp","5187","195","#ifndef ECELL4_CIRCLE_HPP +#define ECELL4_CIRCLE_HPP +#include ""Shape.hpp"" +#include +#include + +namespace ecell4 +{ + +struct Circumference; + +struct Circle : public Shape +{ +public: + + Circle(){} + ~Circle(){} + + Circle(const Real radius, const Real3& center, const Real3 normal) + : radius_(radius), center_(center), normal_(normal) + {} + Circle(const Circle& rhs) + : radius_(rhs.radius_), center_(rhs.center_), normal_(rhs.normal_) + {} + Circle& operator=(const Circle& rhs) + { + radius_ = rhs.radius_; + center_ = rhs.center_; + normal_ = rhs.normal_; + return *this; + } + + Real const& radius() const {return radius_;} + Real3 const& center() const {return center_;} + Real3 const& normal() const {return normal_;} + + Real3 const& position() const {return center_;} + Real3& position() {return center_;} + Real const& size() const {return radius_;} + Real& size() {return radius_;} + dimension_kind dimension() const {return TWO;} + + Real is_inside(const Real3& coord) const + { + return this->distance(coord); + } + Real distance(const Real3& pos) const + { + const std::pair result = this->distance_sq_(pos); + return result.first ? std::sqrt(result.second) : -std::sqrt(result.second); + } + Real distance_sq(const Real3& pos) const + { + return this->distance_sq_(pos).second; + } + + Circumference surface() const; + + Real3 draw_position(std::shared_ptr& rng) const + { + throw NotImplemented(""Circle::draw_position""); + } + + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Circle::test_AABB""); + } + +protected: + + std::pair distance_sq_(const Real3& pos) const + { + const Real dot = dot_product(center_ - pos, normal_); + const bool sign = (dot < 0); // true means + side + const Real3 projection(normal_ * dot); + const Real dist_on_plane2 = length_sq(pos + projection - center_); + if(dist_on_plane2 > radius_ * radius_) + { + const Real dr = std::sqrt(dist_on_plane2) - radius_; + return std::make_pair(sign, length_sq(projection) + dr * dr); + } + else + { + return std::make_pair(sign, length_sq(projection)); + } + } + +protected: + + Real radius_; + Real3 center_; + Real3 normal_; +}; + +struct Circumference : public Shape +{ + Circumference(){} + ~Circumference(){} + + Circumference(const Real radius, const Real3& center, const Real3& normal) + : radius_(radius), center_(center), normal_(normal) + {} + Circumference(const Circumference& rhs) + : radius_(rhs.radius()), center_(rhs.center()), normal_(rhs.normal()) + {} + + Real const& radius() const {return radius_;} + Real3 const& center() const {return center_;} + Real3 const& normal() const {return normal_;} + + Real is_inside(const Real3& coord) const + { + return this->distance(coord); + } + Real distance(const Real3& pos) const + { + const std::pair result = this->distance_sq_(pos); + return result.first ? std::sqrt(result.second) : -std::sqrt(result.second); + } + Real distance_sq(const Real3& pos) const + { + return this->distance_sq_(pos).second; + } + + Circle inside() const {return Circle(radius_, center_, normal_);} + + Real3 draw_position(std::shared_ptr& rng) const + { + throw NotImplemented(""Circumference::draw_position""); + } + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Circumference::test_AABB""); + } + + dimension_kind dimension() const + { + return ONE; + } + +protected: + + std::pair distance_sq_(const Real3& pos) const + { + const Real dot = dot_product(center_ - pos, normal_); + const bool sign = (dot < 0); // true means + side + const Real3 projection(normal_ * dot); + const Real dist_on_plane2 = length_sq(pos + projection - center_); + if(dist_on_plane2 > radius_ * radius_) + { + const Real dr = std::sqrt(dist_on_plane2) - radius_; + return std::make_pair(sign, length_sq(projection) + dr * dr); + } + else + { + return std::make_pair(sign, length_sq(projection)); + } + } + +protected: + + Real radius_; + Real3 center_; + Real3 normal_; +}; + +inline Circumference Circle::surface() const +{ + return Circumference(radius_, center_, normal_); +} + + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const Circle& c) +{ + os << ""Circle(r="" << c.radius() << "", o="" << c.center() + << "", n="" << c.normal() << "")""; + return os; +} + + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const Circumference& c) +{ + os << ""Circumference(r="" << c.radius() << "", o="" << c.center() + << "", n="" << c.normal() << "")""; + return os; +} + + +} // ecell4 +#endif //ECELL4_CIRCLE_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Species.cpp",".cpp","4310","211","#include ""Species.hpp"" + +#include + + +namespace ecell4 +{ + +Species::Species() + : serial_(""""), attributes_() +{ + ; // do nothing +} + +Species::Species(const serial_type& name) + : serial_(name), attributes_() +{ + ; +} + +Species::Species(const Species& another) + : serial_(another.serial()), attributes_(another.attributes_) +{ + ; +} + +Species& Species::operator=(const Species& another) +{ + serial_ = another.serial_; + attributes_ = another.attributes_; + return *this; +} + +Species::Species( + const serial_type& name, const Real& radius, const Real& D, + const std::string location, const Integer& dimension) + : serial_(name), attributes_() +{ + set_attribute(""radius"", radius); + set_attribute(""D"", D); + set_attribute(""location"", location); + set_attribute(""dimension"", dimension); +} + +Species::Species( + const serial_type& name, const Quantity& radius, const Quantity& D, + const std::string location, const Integer& dimension) + : serial_(name), attributes_() +{ + set_attribute(""radius"", radius); + set_attribute(""D"", D); + set_attribute(""location"", location); + set_attribute(""dimension"", dimension); +} + +const Species::serial_type Species::serial() const +{ + return serial_; +} + +bool Species::operator==(const Species& rhs) const +{ + return (serial() == rhs.serial()); +} + +bool Species::operator!=(const Species& rhs) const +{ + return (serial() != rhs.serial()); +} + +bool Species::operator<(const Species& rhs) const +{ + return (serial() < rhs.serial()); +} + +bool Species::operator>(const Species& rhs) const +{ + return (serial() > rhs.serial()); +} + +Integer Species::count(const Species& sp) const +{ + // return count_spmatches(*this, sp); + throw NotSupported(""Function 'Species::count' was deprecated. Rather use 'count_species_matches'""); +} + +const std::vector Species::units() const +{ + std::vector unit_serials; + boost::split(unit_serials, serial_, boost::is_any_of(""."")); + + std::vector units_; + for (std::vector::const_iterator i(unit_serials.begin()); + i != unit_serials.end(); ++i) + { + UnitSpecies usp; + usp.deserialize(*i); + units_.insert(std::lower_bound(units_.begin(), units_.end(), usp), usp); + } + return units_; +} + +void Species::add_unit(const UnitSpecies& usp) +{ + if (usp.name() == """") + { + throw NotSupported(""UnitSpecies must have a name.""); + } + else if (serial_ != """") + { + serial_ += ""."" + usp.serial(); + } + else + { + serial_ = usp.serial(); + } +} + +Species::attribute_type Species::get_attribute(const std::string& key) const +{ + return attributes_.get(key); +} + +std::vector > Species::list_attributes() const +{ + return attributes_.values(); +} + +void Species::set_attributes(const Attribute& attributes) +{ + attributes_ = attributes; +} + +void Species::set_attributes(const Species& sp) +{ + set_attributes(sp.attributes()); +} + +void Species::overwrite_attributes(const Species& sp) +{ + attributes_.overwrite(sp.attributes()); +} + +void Species::remove_attribute(const std::string& key) +{ + attributes_.remove(key); +} + +bool Species::has_attribute(const std::string& key) const +{ + return attributes_.has_key(key); +} + +const Attribute& Species::attributes() const +{ + return attributes_; +} + +Species& Species::D(const std::string& value) +{ + set_attribute(""D"", value); + return (*this); +} + +Species* Species::D_ptr(const std::string& value) +{ + return &(this->D(value)); +} + +Species& Species::radius(const std::string& value) +{ + set_attribute(""radius"", value); + return (*this); +} + +Species* Species::radius_ptr(const std::string& value) +{ + return &(this->radius(value)); +} + +Species& Species::location(const std::string& value) +{ + set_attribute(""location"", value); + return (*this); +} + +Species* Species::location_ptr(const std::string& value) +{ + return &(this->location(value)); +} + +Species& Species::dimension(const std::string& value) +{ + set_attribute(""dimension"", value); + return (*this); +} + +Species* Species::dimension_ptr(const std::string& value) +{ + return &(this->location(value)); +} + +/** for epdp + */ +Species::serial_type Species::name() const +{ + return serial(); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ParticleSpaceRTreeImpl.cpp",".cpp","4307","149","#include +#include + +namespace ecell4 +{ + +void ParticleSpaceRTreeImpl::reset(const Real3& edge_lengths) +{ + this->t_ = 0.0; + this->particle_pool_.clear(); + this->rtree_.clear(); + this->rtree_.reset_boundary(edge_lengths); + return ; +} + +std::vector ParticleSpaceRTreeImpl::list_species() const +{ + std::vector retval; + for (const auto& pidp : rtree_.list_objects()) + { + const Species& sp(pidp.second.species()); + if(std::find(retval.begin(), retval.end(), sp) == retval.end()) + { + retval.push_back(sp); + } + } + return retval; +} + +Integer ParticleSpaceRTreeImpl::num_particles(const Species& sp) const +{ + Integer retval(0); + SpeciesExpressionMatcher sexp(sp); + for(const auto& idset : particle_pool_) + { + const Species target(idset.first); + if(sexp.match(target)) + { + retval += idset.second.size(); + } + } + return retval; +} + +Integer ParticleSpaceRTreeImpl::num_particles_exact(const Species& sp) const +{ + const auto i = particle_pool_.find(sp.serial()); + return (i == particle_pool_.end()) ? 0 : i->second.size(); +} + +Integer ParticleSpaceRTreeImpl::num_molecules(const Species& sp) const +{ + Integer retval(0); + SpeciesExpressionMatcher sexp(sp); + for(const auto& idset : particle_pool_) + { + const Species target(idset.first); + retval += sexp.count(target) * idset.second.size(); + } + return retval; +} + +Integer ParticleSpaceRTreeImpl::num_molecules_exact(const Species& sp) const +{ + return num_particles_exact(sp); +} + +std::vector> +ParticleSpaceRTreeImpl::list_particles(const Species& sp) const +{ + std::vector> retval; + SpeciesExpressionMatcher sexp(sp); + + for(const auto& pidp : rtree_.list_objects()) + { + if(sexp.match(pidp.second.species())) + { + retval.push_back(pidp); + } + } + return retval; +} +std::vector > +ParticleSpaceRTreeImpl::list_particles_exact(const Species& sp) const +{ + std::vector> retval; + + for(const auto& pidp : rtree_.list_objects()) + { + if (pidp.second.species() == sp) + { + retval.push_back(pidp); + } + } + return retval; +} + +std::vector, Real>> +ParticleSpaceRTreeImpl::list_particles_within_radius( + const Real3& pos, const Real& radius) const +{ + std::vector, Real>> list; + this->query_impl(make_intersection_query(pos, radius, + [](const value_type&) noexcept -> bool { + return false; + }), std::back_inserter(list)); + + std::sort(list.begin(), list.end(), utils::pair_second_element_comparator< + std::pair, Real>()); + return list; +} + +std::vector, Real>> +ParticleSpaceRTreeImpl::list_particles_within_radius( + const Real3& pos, const Real& radius, const ParticleID& ignore) const +{ + std::vector, Real>> list; + + this->query_impl(make_intersection_query(pos, radius, + [&ignore](const value_type& pidp) noexcept -> bool { + return pidp.first == ignore; + }), std::back_inserter(list)); + + std::sort(list.begin(), list.end(), utils::pair_second_element_comparator< + std::pair, Real>()); + + return list; +} + +std::vector, Real>> +ParticleSpaceRTreeImpl::list_particles_within_radius( + const Real3& pos, const Real& radius, const ParticleID& ignore1, + const ParticleID& ignore2) const +{ + std::vector, Real>> list; + + this->query_impl(make_intersection_query(pos, radius, + [&ignore1, &ignore2](const value_type& pidp) noexcept -> bool { + return pidp.first == ignore1 || pidp.first == ignore2; + }), std::back_inserter(list)); + + std::sort(list.begin(), list.end(), utils::pair_second_element_comparator< + std::pair, Real>()); + + return list; +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Cone.hpp",".hpp","5268","192","#ifndef ECELL4_CORE_CONE +#define ECELL4_CORE_CONE +#include +#include +#include ""Shape.hpp"" + +namespace ecell4 +{ +struct ConicalSurface; + +struct Cone : public Shape +{ +public: + typedef Real3 position_type; + typedef position_type::value_type length_type; + typedef position_type::value_type value_type; + +public: + + Cone(){} + ~Cone(){} + Cone(const Real3 apex, const Real apex_angl)/* infinite cone */ + : slant_height_(std::numeric_limits::max()), + apex_angle_(apex_angl), apex_(apex) + {} + Cone(const Real3 apex, const Real apex_angl, const Real slant) + : slant_height_(slant), apex_angle_(apex_angl), apex_(apex) + {} + Cone(const Cone& rhs) + : slant_height_(rhs.slant_height_), apex_angle_(rhs.apex_angle_), + apex_(rhs.apex_) + {} + Cone& operator=(const Cone& rhs) + { + slant_height_ = rhs.slant_height_; + apex_angle_ = rhs.apex_angle_; + apex_ = rhs.apex_; + return *this; + } + + Real const& slant_height() const {return slant_height_;} + Real const& apex_angle() const {return apex_angle_;} + Real3 const& apex() const {return apex_;} + + Real3 const& position() const {return apex_;} + Real3& position() {return apex_;} + Real const& size() const {return slant_height_;} + Real& size() {return slant_height_;} + dimension_kind dimension() const {return THREE;} + + Real is_inside(const Real3& coord) const + { + throw NotImplemented(""Cone::is_inside""); + } + Real distance(const Real3& pos) const + { + throw NotImplemented(""Cone::distance""); + } + Real distance_sq(const Real3& pos) const + { + throw NotImplemented(""Cone::distance_sq""); + } + + ConicalSurface surface() const; + + Real3 draw_position(std::shared_ptr& rng) const + { + throw NotImplemented(""Cone::draw_position""); + } + + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Cone::test_AABB""); + } + +protected: + + Real slant_height_;// + Real apex_angle_; + Real3 apex_; + +}; + +struct ConicalSurface : public Shape +{ +public: + typedef Real3 position_type; + typedef position_type::value_type length_type; + typedef position_type::value_type value_type; + +public: + + ConicalSurface(){} + ~ConicalSurface(){} + ConicalSurface(const Real3 apex, const Real apex_angl) + : slant_height_(std::numeric_limits::max()), + apex_angle_(apex_angl), apex_(apex) + {} + ConicalSurface(const Real3 apex, const Real apex_angl, const Real slant) + : slant_height_(slant), apex_angle_(apex_angl), apex_(apex) + {} + + ConicalSurface(const ConicalSurface& rhs) + : slant_height_(rhs.slant_height_), apex_angle_(rhs.apex_angle_), + apex_(rhs.apex_) + {} + ConicalSurface& operator=(const ConicalSurface& rhs) + { + slant_height_ = rhs.slant_height_; + apex_angle_ = rhs.apex_angle_; + apex_ = rhs.apex_; + return *this; + } + + Real const& slant_height() const {return slant_height_;} + Real const& apex_angle() const {return apex_angle_;} + Real3 const& apex() const {return apex_;} + + Real3 const& position() const {return apex_;} + Real3& position() {return apex_;} + Real const& size() const {return slant_height_;} + Real& size() {return slant_height_;} + dimension_kind dimension() const {return THREE;} + + Real is_inside(const Real3& coord) const + { + return distance(coord); + } + Real distance(const Real3& pos) const + { + const std::pair result = this->distance_sq_(pos); + return result.first ? result.second : -(result.second); + } + Real distance_sq(const Real3& pos) const + { + return this->distance_sq_(pos).second; + } + + Cone inside() const {return Cone(apex_, apex_angle_, slant_height_);} + + Real3 draw_position(std::shared_ptr& rng) const + { + throw NotImplemented(""ConicalSurface::draw_position""); + } + + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""ConicalSurface::test_AABB""); + } + +protected: + // pairof(is_outside, dist) + std::pair distance_sq_(const Real3& pos) const + { + throw NotImplemented(""protected: ConicalSurface::distance_sq_""); + } + +protected: + + Real slant_height_; + Real apex_angle_; + Real3 apex_; +}; + +inline ConicalSurface Cone::surface() const +{ + return ConicalSurface(apex_, apex_angle_, slant_height_); +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const Cone& c) +{ + os << ""Cone(apex="" << c.apex() << "", apex_angle = "" << c.apex_angle() + << "", slant_height="" << c.slant_height() << "")""; + return os; +} + + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const ConicalSurface& c) +{ + os << ""ConicalSurface(apex="" << c.apex() << "", apex_angle = "" << c.apex_angle() + << "", slant_height="" << c.slant_height() << "")""; + return os; +} + + +} // ecell4 +#endif //ECELL4_CORE_CONE +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/NetfreeModel.cpp",".cpp","13865","460","#include + +#include ""exceptions.hpp"" +#include ""NetfreeModel.hpp"" + + +namespace ecell4 +{ + +bool NetfreeModel::update_species_attribute(const Species& sp) +{ + species_container_type::iterator i(std::find(species_attributes_.begin(), species_attributes_.end(), sp)); + if (i == species_attributes_.end()) + { + add_species_attribute(sp); + return true; + } + (*i).overwrite_attributes(sp); + return false; +} + +void NetfreeModel::add_species_attribute(const Species& sp, const bool proceed) +{ + species_attributes_.push_back(sp); + species_attributes_proceed_.push_back(proceed); +} + +void NetfreeModel::remove_species_attribute(const Species& sp) +{ + species_container_type::iterator i(std::find(species_attributes_.begin(), species_attributes_.end(), sp)); + if (i == species_attributes_.end()) + { + throw_exception(""The given Speices ["", sp.serial(), ""] was not found""); + } + species_attributes_proceed_.erase( + species_attributes_proceed_.begin() + std::distance(species_attributes_.begin(), i)); + species_attributes_.erase(i); +} + +bool NetfreeModel::has_species_attribute(const Species& sp) const +{ + return has_species_attribute_exact(sp); +} + +bool NetfreeModel::has_species_attribute_exact(const Species& sp) const +{ + species_container_type::const_iterator i( + std::find(species_attributes_.begin(), species_attributes_.end(), sp)); + return (i != species_attributes_.end()); +} + +Species NetfreeModel::apply_species_attributes(const Species& sp) const +{ + Species ret(sp); + species_container_type::const_iterator i(species_attributes_.begin()); + std::vector::const_iterator j(species_attributes_proceed_.begin()); + for (; i != species_attributes_.end() && j != species_attributes_proceed_.end(); ++i, ++j) + { + if (!SpeciesExpressionMatcher(*i).match(sp)) + { + continue; + } + ret.overwrite_attributes(*i); + if (!(*j)) + { + break; + } + } + return ret; +} + +Integer NetfreeModel::apply(const Species& pttrn, const Species& sp) const +{ + return SpeciesExpressionMatcher(pttrn).count(sp); +} + +std::vector NetfreeModel::query_reaction_rules( + const Species& sp) const +{ + ReactionRule::reactant_container_type reactants(1, sp); + std::vector retval; + for (reaction_rule_container_type::const_iterator i(reaction_rules_.begin()); + i != reaction_rules_.end(); ++i) + { + const std::vector generated = (*i).generate(reactants); + // retval.insert(retval.end(), generated.begin(), generated.end()); + retval.reserve(retval.size() + generated.size()); + for (std::vector::const_iterator j(generated.begin()); + j != generated.end(); ++j) + { + // const ReactionRule rr = create_reaction_rule_formatted(*j); + const ReactionRule rr = format_reaction_rule_with_nosort(*j); + std::vector::iterator + it = std::find(retval.begin(), retval.end(), rr); + if (it == retval.end()) + { + retval.push_back(rr); + } + else + { + (*it).set_k((*it).k() + rr.k()); + } + } + } + return retval; +} + +struct reaction_rule_product_unary_predicator +{ + typedef ReactionRule element_type; + + reaction_rule_product_unary_predicator(const element_type& target) + : target_(target) + { + ; // do nothing + } + + bool operator()(const element_type& v) + { + return v.products() == target_.products(); + } + +protected: + + element_type target_; +}; + +std::vector generate_reaction_rules( + const ReactionRule& org, const Species& sp1, const Species& sp2) +{ + if (org.reactants().size() != 2) + { + return std::vector(0); + } + + ReactionRule::reactant_container_type reactants(2); + reactants[0] = sp1; + reactants[1] = sp2; + std::vector res = org.generate(reactants); + + if (org.reactants()[0] != org.reactants()[1]) + { + reactants[0] = sp2; + reactants[1] = sp1; + std::vector _res = org.generate(reactants); + std::copy(_res.begin(), _res.end(), back_inserter(res)); + } + return res; +} + +std::vector NetfreeModel::query_reaction_rules( + const Species& sp1, const Species& sp2) const +{ + std::vector retval; + for (reaction_rule_container_type::const_iterator i(reaction_rules_.begin()); + i != reaction_rules_.end(); ++i) + { + const std::vector generated = generate_reaction_rules(*i, sp1, sp2); + // retval.insert(retval.end(), generated.begin(), generated.end()); + retval.reserve(retval.size() + generated.size()); + for (std::vector::const_iterator j(generated.begin()); + j != generated.end(); ++j) + { + // const ReactionRule rr = create_reaction_rule_formatted(*j); + const ReactionRule rr = format_reaction_rule_with_nosort(*j); + std::vector::iterator + it = std::find(retval.begin(), retval.end(), rr); + if (it == retval.end()) + { + retval.push_back(rr); + } + else + { + (*it).set_k((*it).k() + rr.k()); + } + } + } + + if (effective_) + { + for (std::vector::iterator i(retval.begin()); i != retval.end(); ++i) + { + const ReactionRule& rr(*i); + if (rr.reactants()[0] == rr.reactants()[1]) + { + (*i).set_k(rr.k() * 0.5); + } + } + } + return retval; +} + +std::vector NetfreeModel::apply( + const ReactionRule& rr, const ReactionRule::reactant_container_type& reactants) const +{ + return rr.generate(reactants); +} + +void NetfreeModel::add_reaction_rule(const ReactionRule& rr) +{ + reaction_rules_.push_back(rr); +} + +void NetfreeModel::remove_reaction_rule(const ReactionRule& rr) +{ + reaction_rule_container_type::iterator i(std::remove(reaction_rules_.begin(), reaction_rules_.end(), rr)); + if (i == reaction_rules_.end()) + { + throw NotFound(""The given reaction rule was not found.""); + } + reaction_rules_.erase(i, reaction_rules_.end()); +} + +bool NetfreeModel::has_reaction_rule(const ReactionRule& rr) const +{ + reaction_rule_container_type::const_iterator + i(std::find(reaction_rules_.begin(), reaction_rules_.end(), rr)); + return (i != reaction_rules_.end()); +} + +std::shared_ptr NetfreeModel::expand( + const std::vector& sp, const Integer max_itr, + const std::map& max_stoich) const +{ + return extras::generate_network_from_netfree_model( + *this, sp, max_itr, max_stoich).first; +} + + +std::shared_ptr NetfreeModel::expand( + const std::vector& sp, const Integer max_itr) const +{ + return extras::generate_network_from_netfree_model( + *this, sp, max_itr).first; +} + +std::shared_ptr NetfreeModel::expand( + const std::vector& sp) const +{ + const Integer max_itr(30); + std::pair, bool> + retval(extras::generate_network_from_netfree_model(*this, sp, max_itr)); + if (retval.second) + { + return retval.first; + } + else + { + return std::shared_ptr(); // return null + } +} + +namespace extras +{ + +bool check_stoichiometry(const Species& sp, + const std::map& max_stoich) +{ + for (std::map::const_iterator i(max_stoich.begin()); + i != max_stoich.end(); ++i) + { + if (static_cast(SpeciesExpressionMatcher((*i).first).count(sp)) > (*i).second) + { + return false; + } + } + return true; +} + +bool check_stoichiometry(const ReactionRule& rr, + const std::map& max_stoich) +{ + for (ReactionRule::product_container_type::const_iterator + i(rr.products().begin()); i != rr.products().end(); ++i) + { + if (!check_stoichiometry(*i, max_stoich)) + { + return false; + } + } + return true; +} + +void __add_reaction_rules( + const std::vector& reaction_rules, + std::vector& reactions, std::vector& newseeds, + const std::vector& seeds, + const std::map& max_stoich) +{ + for (std::vector::const_iterator i(reaction_rules.begin()); + i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + if (!check_stoichiometry(rr, max_stoich)) + { + continue; + } + + reactions.push_back(rr); + + for (ReactionRule::product_container_type::const_iterator + j(rr.products().begin()); j != rr.products().end(); ++j) + { + const Species sp(format_species(*j)); + if (std::find(newseeds.begin(), newseeds.end(), sp) + == newseeds.end() + && std::find(seeds.begin(), seeds.end(), sp) + == seeds.end()) + { + newseeds.push_back(sp); + } + } + } +} + +void __generate_recurse( + const NetfreeModel& nfm, std::vector& reactions, + std::vector& seeds1, std::vector& seeds2, + const std::map& max_stoich) +{ + std::vector newseeds; + seeds2.insert(seeds2.begin(), seeds1.begin(), seeds1.end()); + + for (NetfreeModel::reaction_rule_container_type::const_iterator + i(nfm.reaction_rules().begin()); i != nfm.reaction_rules().end(); ++i) + { + const ReactionRule& rr(*i); + + switch (rr.reactants().size()) + { + case 0: + continue; + case 1: + for (std::vector::const_iterator j(seeds1.begin()); + j != seeds1.end(); ++j) + { + ReactionRule::reactant_container_type reactants(1); + reactants[0] = *j; + __add_reaction_rules( + rr.generate(reactants), reactions, newseeds, seeds2, max_stoich); + } + break; + case 2: + for (std::vector::const_iterator j(seeds1.begin()); + j != seeds1.end(); ++j) + { + const std::vector::const_iterator start( + seeds2.begin() + + std::distance::const_iterator>( + seeds1.begin(), j)); + for (std::vector::const_iterator + k(start); k != seeds2.end(); ++k) + { + __add_reaction_rules( + generate_reaction_rules(rr, *j, *k), + reactions, newseeds, seeds2, max_stoich); + } + } + break; + default: + throw NotImplemented( + ""No reaction rule with more than two reactants is accepted.""); + } + } + + seeds1.swap(newseeds); +} + +std::pair, bool> generate_network_from_netfree_model( + const NetfreeModel& nfm, const std::vector& seeds, const Integer max_itr, + const std::map& max_stoich) +{ + std::vector reactions; + std::vector seeds1; + std::vector seeds2; + + for (std::vector::const_iterator i(seeds.begin()); + i != seeds.end(); ++i) + { + const Species sp(format_species(*i)); + if (std::find(seeds1.begin(), seeds1.end(), sp) + == seeds1.end()) + { + seeds1.push_back(sp); + } + } + + for (NetfreeModel::reaction_rule_container_type::const_iterator + i(nfm.reaction_rules().begin()); i != nfm.reaction_rules().end(); ++i) + { + const ReactionRule& rr(*i); + if (rr.reactants().size() == 0 && check_stoichiometry(rr, max_stoich)) + { + reactions.push_back(rr); + for (ReactionRule::product_container_type::const_iterator + j(rr.products().begin()); j != rr.products().end(); ++j) + { + const Species sp(format_species(*j)); + if (std::find(seeds1.begin(), seeds1.end(), sp) + == seeds1.end()) + { + seeds1.push_back(sp); + } + } + } + } + + Integer cnt(0); + while (seeds1.size() > 0 && cnt < max_itr) + { + __generate_recurse(nfm, reactions, seeds1, seeds2, max_stoich); + cnt += 1; + } + + bool is_completed; + if (seeds1.size() != 0) + { + is_completed = false; + seeds2.insert(seeds2.begin(), seeds1.begin(), seeds1.end()); + } + else + { + is_completed = true; + } + + std::shared_ptr nwm(new NetworkModel()); + for (std::vector::const_iterator i(seeds2.begin()); + i != seeds2.end(); ++i) + { + (*nwm).add_species_attribute(nfm.apply_species_attributes(*i)); + } + if (nfm.effective()) + { + for (std::vector::const_iterator i(reactions.begin()); + i != reactions.end(); ++i) + { + ReactionRule rr(format_reaction_rule(*i)); + if (rr.reactants().size() == 2 && rr.reactants()[0] == rr.reactants()[1]) + { + rr.set_k(rr.k() * 0.5); + } + + (*nwm).add_reaction_rule(rr); + } + } + else + { + for (std::vector::const_iterator i(reactions.begin()); + i != reactions.end(); ++i) + { + (*nwm).add_reaction_rule(format_reaction_rule(*i)); + } + } + return std::make_pair(nwm, is_completed); +} + +} // extras + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/LatticeSpaceCellListImpl.cpp",".cpp","6020","224","#include ""LatticeSpaceCellListImpl.hpp"" +#include ""StructureType.hpp"" + +namespace ecell4 +{ + +Integer LatticeSpaceCellListImpl::num_molecules(const Species &sp) const +{ + Integer count(0); + SpeciesExpressionMatcher sexp(sp); + + for (const auto &info : molecule_pools_) + { + const Integer cnt(sexp.count(info.first)); + if (cnt > 0) + { + const std::shared_ptr &vp(info.second); + count += vp->size() * cnt; + } + } + return count; +} + +/* + * Change the Species and coordinate of a Voxel with ParticleID, pid, to + * species and coordinate respectively and return false. + * If no Voxel with pid is found, create a new Voxel at + * coordiante() and return true. + */ +bool LatticeSpaceCellListImpl::update_voxel(const ParticleID &pid, + const Species &species, + const coordinate_type to_coord) +{ + if (!is_in_range(to_coord)) + { + throw NotSupported(""Out of bounds""); + } + + std::shared_ptr new_vp(find_voxel_pool(species)); + std::shared_ptr dest_vp(get_voxel_pool_at(to_coord)); + + if (dest_vp != new_vp->location()) + { + throw NotSupported(""Mismatch in the location.""); + } + + if (pid != ParticleID()) + { + const std::pair, coordinate_type> target( + __get_coordinate(pid)); + const coordinate_type &from_coord(target.second); + if (from_coord != -1) + { + // move + target.first->remove_voxel_if_exists(from_coord); + + // XXX: use location? + dest_vp->replace_voxel(to_coord, from_coord); + + new_vp->add_voxel(coordinate_id_pair_type(pid, to_coord)); + + if (!dest_vp->is_vacant()) + { + update_matrix(from_coord, dest_vp); + update_matrix(to_coord, new_vp); + } + else + { + update_matrix(from_coord, to_coord, new_vp); + } + return true; + } + } + + // new + dest_vp->remove_voxel_if_exists(to_coord); + + new_vp->add_voxel(coordinate_id_pair_type(pid, to_coord)); + update_matrix(to_coord, new_vp); + return true; +} + +bool LatticeSpaceCellListImpl::add_voxel(const Species &sp, + const ParticleID &pid, + const coordinate_type &coord) +{ + std::shared_ptr vpool(find_voxel_pool(sp)); + std::shared_ptr location(get_voxel_pool_at(coord)); + + if (vpool->location() != location) + return false; + + location->remove_voxel_if_exists(coord); + vpool->add_voxel(coordinate_id_pair_type(pid, coord)); + update_matrix(coord, vpool); + + return true; +} + +std::pair, + LatticeSpaceCellListImpl::coordinate_type> +LatticeSpaceCellListImpl::__get_coordinate(const ParticleID &pid) +{ + for (auto &info : molecule_pools_) + { + const std::shared_ptr &vp(info.second); + MoleculePool::container_type::const_iterator j(vp->find(pid)); + if (j != vp->end()) + { + return std::make_pair(vp, (*j).coordinate); + } + } + return std::make_pair(std::shared_ptr(), + -1); // XXX: a bit dirty way +} + +std::pair, + LatticeSpaceCellListImpl::coordinate_type> +LatticeSpaceCellListImpl::__get_coordinate(const ParticleID &pid) const +{ + for (const auto &info : molecule_pools_) + { + const std::shared_ptr &vp(info.second); + MoleculePool::container_type::const_iterator j(vp->find(pid)); + if (j != vp->end()) + { + } + } + return std::make_pair(std::shared_ptr(), + -1); // XXX: a bit dirty way +} + +std::shared_ptr LatticeSpaceCellListImpl::get_voxel_pool_at( + const LatticeSpaceCellListImpl::coordinate_type &coord) const +{ + /** + XXX: This may not work + */ + if (!is_in_range(coord)) + { + throw NotSupported(""Out of bounds""); + } + + if (!is_inside(coord)) + { + if (is_periodic_) + { + return periodic_; + } + else + { + return border_; + } + } + + // for (spmap::iterator itr(spmap_.begin()); + // itr != spmap_.end(); ++itr) + // { + // VoxelPool& vp((*itr).second); + // if (vp.is_vacant()) + // { + // continue; + // } + + // VoxelPool::container_type::const_iterator j(vp.find(coord)); + // if (j != vp.end()) + // { + // return (&vp); + // } + // } + + const cell_type &cell(matrix_[coordinate2index(coord)]); + if (cell.size() == 0) + { + return vacant_; + } + + cell_type::const_iterator i(find_from_cell(coord, cell)); + if (i != cell.end()) + { + return (*i).first; + } + + return vacant_; +} + +void LatticeSpaceCellListImpl::add_structure( + const Species &sp, const std::shared_ptr &s, + const std::string loc) +{ + make_structure_type(sp, loc); + + structure_container_type::const_iterator i(structures_.find(sp)); + if (i != structures_.end()) + { + throw NotSupported(""not supported yet.""); + } + structures_.insert(std::make_pair(sp, s)); +} + +const std::shared_ptr & +LatticeSpaceCellListImpl::get_structure(const Species &sp) const +{ + structure_container_type::const_iterator i(structures_.find(sp)); + if (i == structures_.end()) + { + throw NotFound(""not found.""); + } + return (*i).second; +} + +const Shape::dimension_kind +LatticeSpaceCellListImpl::get_structure_dimension(const Species &sp) const +{ + structure_container_type::const_iterator i(structures_.find(sp)); + if (i == structures_.end()) + { + return Shape::THREE; // Default value (ex. for VACANT type) + } + return (*i).second->dimension(); +} + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/CompartmentSpace.hpp",".hpp","6183","262","#ifndef ECELL4_COMPARTMENT_SPACE_HPP +#define ECELL4_COMPARTMENT_SPACE_HPP + +#include ""types.hpp"" +#include ""exceptions.hpp"" +#include ""Species.hpp"" +#include ""Real3.hpp"" +// #include ""Space.hpp"" + +#ifdef WITH_HDF5 +#include ""CompartmentSpaceHDF5Writer.hpp"" +#endif + +namespace ecell4 +{ + +class CompartmentSpace + // : public Space +{ +public: + + CompartmentSpace() + : t_(0.0) + { + ; + } + + virtual ~CompartmentSpace() + { + ; // do nothing + } + + // SpaceTraits + + const Real t() const + { + return t_; + } + + void set_t(const Real& t) + { + if (t < 0.0) + { + throw std::invalid_argument(""the time must be positive.""); + } + t_ = t; + } + + // CompartmentSpaceTraits + + virtual const Real3& edge_lengths() const + { + throw NotImplemented(""edge_lengths() not implemented""); + } + + virtual void reset(const Real3& edge_lengths) + { + throw NotImplemented( + ""reset(const Real3&) not implemented""); + } + + /** + * get volume. + * this function is a part of the trait of CompartmentSpace. + * @return a volume (m^3) Real + */ + virtual const Real volume() const + { + throw NotImplemented(""volume() not implemented""); + } + + /** + * get the number of molecules + * this function is a part of the trait of CompartmentSpace. + * @param sp a species + * @return a number of molecules Integer + */ + + virtual Integer num_molecules(const Species& sp) const + { + return num_molecules_exact(sp); + } + + virtual Integer num_molecules_exact(const Species& sp) const + { + throw NotImplemented(""num_molecules_exact(const Species&) not implemented""); + } + + virtual Real get_value(const Species& sp) const + { + return static_cast(num_molecules(sp)); + } + + virtual Real get_value_exact(const Species& sp) const + { + return static_cast(num_molecules_exact(sp)); + } + + /** + * get all species whitin the space. + * this function is a part of the trait of CompartmentSpace. + * @return a list of species + */ + virtual std::vector list_species() const + { + throw NotImplemented(""list_species() not implemented""); + } + + virtual bool has_species(const Species& sp) const + { + throw NotImplemented(""has_species(const Species&) not implemented""); + } + + // CompartSpace member functions + + /** + * set volume. + * this function is a member of CompartmentSpace. + * @param volume a nonzero positive Real value + */ + virtual void set_volume(const Real& volume) = 0; + + /** + * increase the number of molecules. + * this function is a member of CompartmentSpace. + * @param sp a species + * @param num a number of molecules + */ + virtual void add_molecules(const Species& sp, const Integer& num) = 0; + + /** + * decrease the number of molecules. + * this function is a member of CompartmentSpace. + * @param sp a species + * @param num a number of molecules + */ + virtual void remove_molecules(const Species& sp, const Integer& num) = 0; + + virtual void set_value(const Species& sp, const Real value) + { + const Integer num1 = static_cast(value); + const Integer num2 = num_molecules_exact(sp); + if (num1 > num2) + { + add_molecules(sp, num1 - num2); + } + else if (num1 < num2) + { + remove_molecules(sp, num2 - num1); + } + } + +#ifdef WITH_HDF5 + // Optional members + + virtual void save_hdf5(H5::Group* root) const = 0; + virtual void load_hdf5(const H5::Group& root) = 0; +#endif + +protected: + + Real t_; +}; + +class CompartmentSpaceVectorImpl + : public CompartmentSpace +{ +protected: + + typedef CompartmentSpace base_type; + typedef std::vector num_molecules_container_type; + typedef std::vector species_container_type; + typedef std::unordered_map< + Species, num_molecules_container_type::size_type> species_map_type; + +public: + + CompartmentSpaceVectorImpl(const Real3& edge_lengths) + { + reset(edge_lengths); + } + + const Real3& edge_lengths() const + { + return edge_lengths_; + } + + void reset(const Real3& edge_lengths) + { + base_type::t_ = 0.0; + index_map_.clear(); + num_molecules_.clear(); + species_.clear(); + + for (Real3::size_type dim(0); dim < 3; ++dim) + { + if (edge_lengths[dim] <= 0) + { + throw std::invalid_argument(""the edge length must be positive.""); + } + } + + edge_lengths_ = edge_lengths; + volume_ = edge_lengths[0] * edge_lengths[1] * edge_lengths[2]; + } + + // CompartmentSpaceTraits + + const Real volume() const; + Integer num_molecules(const Species& sp) const; + Integer num_molecules_exact(const Species& sp) const; + bool has_species(const Species& sp) const; + + // CompartmentSpace member functions + + void set_volume(const Real& volume); + void add_molecules(const Species& sp, const Integer& num); + void remove_molecules(const Species& sp, const Integer& num); + + // Optional members + + std::vector list_species() const; + + virtual void save(const std::string& filename) const + { + throw NotSupported( + ""save(const std::string) is not supported by this space class""); + } + +#ifdef WITH_HDF5 + void save_hdf5(H5::Group* root) const + { + typedef CompartmentSpaceHDF5Traits traits_type; + save_compartment_space(*this, root); + } + + void load_hdf5(const H5::Group& root) + { + typedef CompartmentSpaceHDF5Traits traits_type; + load_compartment_space(root, this); + } +#endif + +protected: + + void reserve_species(const Species& sp); + void release_species(const Species& sp); + +protected: + + Real3 edge_lengths_; + Real volume_; + + num_molecules_container_type num_molecules_; + species_container_type species_; + species_map_type index_map_; +}; + +} // ecell4 + +#endif /* ECELL4_COMPARTMENT_SPACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/shape_operators.hpp",".hpp","10654","498","#ifndef ECELL4_SHAPE_OPERATORS +#define ECELL4_SHAPE_OPERATORS + +#include ""exceptions.hpp"" +#include ""Shape.hpp"" + +namespace ecell4 +{ + +struct Surface + : public Shape +{ +public: + + Surface() + { + ; + } + + Surface(const std::shared_ptr& root) + : root_(root) + { + ; + } + + Surface(const Surface& other) + : root_(other.root_) + { + ; + } + + ~Surface() + { + ; // do nothing + } + + virtual dimension_kind dimension() const + { + return TWO; + } + + virtual Real is_inside(const Real3& coord) const + { + return root_->is_inside(coord); + } + + virtual Real3 draw_position( + std::shared_ptr& rng) const + { + throw NotSupported(""draw_position is not supported.""); + } + + virtual bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotSupported(""test_AABB is not supported.""); + } + + virtual void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + root_->bounding_box(edge_lengths, lower, upper); + } + + const std::shared_ptr& root() const + { + return root_; + } + +protected: + + std::shared_ptr root_; +}; + +struct Union + : public Shape +{ +public: + + Union(const std::shared_ptr& a, + const std::shared_ptr& b) + : a_(a), b_(b) + { + ; + } + + Union(const Union& other) + : a_(other.a_), b_(other.b_) + { + ; + } + + ~Union() + { + ; // do nothing + } + + virtual dimension_kind dimension() const + { + return a_->dimension(); + } + + virtual Real is_inside(const Real3& coord) const + { + const Real retval1 = a_->is_inside(coord); + const Real retval2 = b_->is_inside(coord); + return std::min(retval1, retval2); + } + + virtual Real3 draw_position( + std::shared_ptr& rng) const + { + throw NotImplemented(""not implemented yet""); + } + + virtual bool test_AABB(const Real3& l, const Real3& u) const + { + return (a_->test_AABB(l, u) || b_->test_AABB(l, u)); + } + + virtual void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + a_->bounding_box(edge_lengths, lower, upper); + + Real3 l, u; + b_->bounding_box(edge_lengths, l, u); + for (unsigned int dim(0); dim < 3; ++dim) + { + lower[dim] = std::min(lower[dim], l[dim]); + upper[dim] = std::max(upper[dim], u[dim]); + } + } + + Surface surface() const + { + if (dimension() == TWO) + { + throw NotSupported(""This union object is two-dimensional""); + } + return Surface(std::shared_ptr(new Union(*this))); + } + + const std::shared_ptr& one() const + { + return a_; + } + + const std::shared_ptr& another() const + { + return b_; + } + +protected: + + std::shared_ptr a_; + std::shared_ptr b_; +}; + +struct Complement + : public Shape +{ +public: + + Complement(const std::shared_ptr& a, + const std::shared_ptr& b) + : a_(a), b_(b) + { + ; + } + + Complement(const Complement& other) + : a_(other.a_), b_(other.b_) + { + ; + } + + ~Complement() + { + ; // do nothing + } + + virtual dimension_kind dimension() const + { + return a_->dimension(); + } + + virtual Real is_inside(const Real3& coord) const + { + if (b_->is_inside(coord) > 0) + { + return a_->is_inside(coord); + } + else + { + return std::numeric_limits::infinity(); + } + } + + virtual Real3 draw_position( + std::shared_ptr& rng) const + { + throw NotImplemented(""not implemented yet""); + } + + virtual bool test_AABB(const Real3& l, const Real3& u) const + { + return (a_->test_AABB(l, u) && !b_->test_AABB(l, u)); + } + + virtual void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + return a_->bounding_box(edge_lengths, lower, upper); + } + + Surface surface() const + { + if (dimension() == TWO) + { + throw NotSupported(""This complement object is two-dimensional""); + } + return Surface(std::shared_ptr(new Complement(*this))); + } + + const std::shared_ptr& one() const + { + return a_; + } + + const std::shared_ptr& another() const + { + return b_; + } + +protected: + + std::shared_ptr a_; + std::shared_ptr b_; +}; + +struct AffineTransformation + : public Shape +{ +public: + + AffineTransformation() + : root_(), a0_(1, 0, 0), a1_(0, 1, 0), a2_(0, 0, 1), b_() + { + ; + } + + AffineTransformation(const std::shared_ptr& root) + : root_(root), a0_(1, 0, 0), a1_(0, 1, 0), a2_(0, 0, 1), b_() + { + ; + } + + AffineTransformation(const std::shared_ptr& root, const Real3& first, const Real3& second, const Real3& third, const Real3& shift) + : root_(root), a0_(first), a1_(second), a2_(third), b_(shift) + { + ; + } + + AffineTransformation(const AffineTransformation& other) + : root_(other.root_), + a0_(other.a0_), a1_(other.a1_), a2_(other.a2_), b_(other.b_) + { + ; + } + + ~AffineTransformation() + { + ; // do nothing + } + + virtual dimension_kind dimension() const + { + return root_->dimension(); + } + + virtual Real is_inside(const Real3& pos) const + { + Real3 p(pos); + invmap(p); + return root_->is_inside(p); + } + + virtual Real3 draw_position( + std::shared_ptr& rng) const + { + Real3 pos = root_->draw_position(rng); + map(pos); + return pos; + } + + virtual bool test_AABB(const Real3& l, const Real3& u) const + { + Real3 lower(l), upper(u); + invmap(lower); + invmap(upper); + return root_->test_AABB(lower, upper); + } + + virtual void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + root_->bounding_box(edge_lengths, lower, upper); + map(lower); + map(upper); + } + + void translate(const Real3& b) + { + b_ += b; + } + + void rescale(const Real3& a) + { + if (a[0] == 0 || a[1] == 0 || a[2] == 0) + { + throw std::invalid_argument( + ""rescaling factors must be non-zero.""); + } + + a0_[0] *= a[0]; + a0_[1] *= a[1]; + a0_[2] *= a[2]; + a1_[0] *= a[0]; + a1_[1] *= a[1]; + a1_[2] *= a[2]; + a2_[0] *= a[0]; + a2_[1] *= a[1]; + a2_[2] *= a[2]; + b_[0] *= a[0]; + b_[1] *= a[1]; + b_[2] *= a[2]; + } + + void xroll(const Real& theta) + { + const double c = cos(theta); + const double s = sin(theta); + + double tmp; + + tmp = a1_[0] * c - a2_[0] * s; + a2_[0] = a1_[0] * s + a2_[0] * c; + a1_[0] = tmp; + + tmp = a1_[1] * c - a2_[1] * s; + a2_[1] = a1_[1] * s + a2_[1] * c; + a1_[1] = tmp; + + tmp = a1_[2] * c - a2_[2] * s; + a2_[2] = a1_[2] * s + a2_[2] * c; + a1_[2] = tmp; + + tmp = b_[1] * c - b_[2] * s; + b_[2] = b_[1] * s + b_[2] * c; + b_[1] = tmp; + } + + void yroll(const Real& theta) + { + const double c = cos(theta); + const double s = sin(theta); + + double tmp; + + tmp = a0_[0] * c + a2_[0] * s; + a2_[0] = a0_[0] * -s + a2_[0] * c; + a0_[0] = tmp; + + tmp = a0_[1] * c + a2_[1] * s; + a2_[1] = a0_[1] * -s + a2_[1] * c; + a0_[1] = tmp; + + tmp = a0_[2] * c + a2_[2] * s; + a2_[2] = a0_[2] * -s + a2_[2] * c; + a0_[2] = tmp; + + tmp = b_[0] * c + b_[2] * s; + b_[2] = b_[0] * -s + b_[2] * c; + b_[0] = tmp; + } + + void zroll(const Real& theta) + { + const double c = cos(theta); + const double s = sin(theta); + + double tmp; + + tmp = a0_[0] * c - a1_[0] * s; + a1_[0] = a0_[0] * s + a1_[0] * c; + a0_[0] = tmp; + + tmp = a0_[1] * c - a1_[1] * s; + a1_[1] = a0_[1] * s + a1_[1] * c; + a0_[1] = tmp; + + tmp = a0_[2] * c - a1_[2] * s; + a1_[2] = a0_[2] * s + a1_[2] * c; + a0_[2] = tmp; + + tmp = b_[0] * c - b_[1] * s; + b_[1] = b_[0] * s + b_[1] * c; + b_[0] = tmp; + } + + Surface surface() const + { + if (dimension() == TWO) + { + throw NotSupported(""This affine object is two-dimensional""); + } + return Surface( + std::shared_ptr(new AffineTransformation(*this))); + } + + const Real3 first() const + { + return a0_; + } + + const Real3 second() const + { + return a1_; + } + + const Real3 third() const + { + return a2_; + } + + const Real3 shift() const + { + return b_; + } + + const std::shared_ptr& root() const + { + return root_; + } + +protected: + + inline void map(Real3& p) const + { + p[0] = dot_product(p, a0_) + b_[0]; + p[1] = dot_product(p, a1_) + b_[1]; + p[2] = dot_product(p, a2_) + b_[2]; + } + + inline void invmap(Real3& p) const + { + double det = 0.0; + det += a0_[0] * a1_[1] * a2_[2]; + det += a1_[0] * a2_[1] * a0_[2]; + det += a2_[0] * a0_[1] * a1_[2]; + det -= a2_[0] * a1_[1] * a0_[2]; + det -= a1_[0] * a0_[1] * a2_[2]; + det -= a0_[0] * a2_[1] * a1_[2]; + + if (det == 0) + { + throw IllegalState( + ""The determinant of an Affine matrix is equal to zero.""); + } + + const Real3 inva0(a1_[1] * a2_[2] - a1_[2] * a2_[1], + a0_[2] * a2_[1] - a0_[1] * a2_[2], + a0_[1] * a1_[2] - a0_[2] * a1_[1]); + const Real3 inva1(a1_[2] * a2_[0] - a1_[0] * a2_[2], + a0_[0] * a2_[2] - a0_[2] * a2_[0], + a0_[2] * a1_[0] - a0_[0] * a1_[2]); + const Real3 inva2(a1_[0] * a2_[1] - a1_[1] * a2_[0], + a0_[1] * a2_[0] - a0_[0] * a2_[1], + a0_[0] * a1_[1] - a0_[1] * a1_[0]); + + Real3 tmp = p - b_; + p[0] = dot_product(tmp, inva0) / det; + p[1] = dot_product(tmp, inva1) / det; + p[2] = dot_product(tmp, inva2) / det; + } + +protected: + + std::shared_ptr root_; + + Real3 a0_, a1_, a2_; + Real3 b_; +}; + +} + +#endif /* ECELL4_SHAPE_OPERATORS */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/geometry.hpp",".hpp","570","22","#ifndef ECELL4_GEOMETRY_HPP +#define ECELL4_GEOMETRY_HPP +#include +#include +#include +#include + +namespace ecell4 +{ + +inline Real calc_angle(const Real3& lhs, const Real3& rhs) +{ + const Real cosine = dot_product(lhs, rhs) / + std::sqrt(length_sq(lhs) * length_sq(rhs)); + return std::acos(boost::algorithm::clamp(cosine, -1.0, 1.0)); +} + +Real3 rotate(const Real angle, const Real3& axis, const Real3& target); + +} // ecell4 +#endif// ECELL4_GEOMETRY_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/VoxelSpaceBase.hpp",".hpp","9036","314","#ifndef ECELL4_VOXELSPACEBASE_HPP +#define ECELL4_VOXELSPACEBASE_HPP + +#include +#include +#include +#include +#include +#include + +#include ""Context.hpp"" +#include ""Integer3.hpp"" +#include ""MoleculePool.hpp"" +#include ""Particle.hpp"" +#include ""Shape.hpp"" +#include ""VacantType.hpp"" +#include ""VoxelPool.hpp"" +#include ""VoxelView.hpp"" + +#ifdef WITH_HDF5 +#include ""LatticeSpaceHDF5Writer.hpp"" +#endif + +namespace ecell4 +{ + +#ifdef WIN32_MSC +double rint(const double x); +double round(const double x); +#endif + +template +static inline std::string get_location_serial(T vp) +{ + if (vp == NULL || vp->location() == NULL || vp->location()->is_vacant()) + { + return """"; + } + + return vp->location()->species().serial(); +} + +class VoxelSpaceBase +{ +public: + typedef Integer coordinate_type; + typedef VoxelPool::coordinate_id_pair_type coordinate_id_pair_type; + +protected: + typedef std::unordered_map> + voxel_pool_map_type; + + typedef std::unordered_map> + molecule_pool_map_type; + +public: + /* + * Constructor and Destructor + */ + VoxelSpaceBase(const Real &voxel_radius) + : t_(0.0), voxel_radius_(voxel_radius), vacant_(VacantType::allocate()) + { + } + + virtual ~VoxelSpaceBase() {} + + /* + * Static Members + */ + + static inline Real calculate_voxel_volume(const Real r) + { + return 4.0 * sqrt(2.0) * r * r * r; + } + + static inline Real3 calculate_hcp_lengths(const Real voxel_radius) + { + return Real3(voxel_radius / sqrt(3.0), // HCP_L + voxel_radius * sqrt(8.0 / 3.0), // HCP_X + voxel_radius * sqrt(3.0)); // HCP_Y + } + + static inline Integer3 calculate_shape(const Real3 &edge_lengths, + const Real &voxel_radius, + const bool is_periodic) + { + const Real3 hcpLXY = calculate_hcp_lengths(voxel_radius); + const Real lengthX = edge_lengths[0]; + const Real lengthY = edge_lengths[1]; + const Real lengthZ = edge_lengths[2]; + + Integer col_size = (Integer)rint(lengthX / hcpLXY[1]) + 1; + Integer layer_size = (Integer)rint(lengthY / hcpLXY[2]) + 1; + Integer row_size = (Integer)rint((lengthZ / 2) / voxel_radius) + 1; + + if (is_periodic) + { + // The number of voxels in each axis must be even for a periodic + // boundary. + col_size = (col_size % 2 == 0 ? col_size : col_size + 1); + layer_size = (layer_size % 2 == 0 ? layer_size : layer_size + 1); + row_size = (row_size % 2 == 0 ? row_size : row_size + 1); + } + + return Integer3(col_size, row_size, layer_size); + } + + static inline Real calculate_volume(const Real3 &edge_lengths, + const Real &voxel_radius, + const bool is_periodic) + { + const Integer3 shape = + calculate_shape(edge_lengths, voxel_radius, is_periodic); + return static_cast(shape[0] * shape[1] * shape[2]) * + calculate_voxel_volume(voxel_radius); + } + + /* + * Space Traits + */ + + const Real t() const { return t_; } + + void set_t(const Real &t) + { + if (t < 0.0) + { + throw std::invalid_argument(""the time must be positive.""); + } + t_ = t; + } + + /** + * get the axes lengths of a cuboidal region. + * @return edge lengths Real3 + */ + virtual const Real3 &edge_lengths() const + { + throw NotSupported( + ""edge_lengths() is not supported by this space class""); + } + + /** + * get volume. + * @return a volume (m^3) Real + */ + const Real volume() const { return actual_size() * voxel_volume(); } + + virtual void save(const std::string &filename) const + { + throw NotSupported( + ""save(const std::string) is not supported by this space class""); + } + +#ifdef WITH_HDF5 + virtual void save_hdf5(H5::Group *root) const + { + throw NotSupported( + ""save_hdf5(H5::Group* root) is not supported by this space class""); + } + + virtual void load_hdf5(const H5::Group &root) + { + throw NotSupported(""load_hdf5(const H5::Group& root) is not supported "" + ""by this space class""); + } +#endif + + /* + * CompartmentSpace Traits + */ + std::vector list_species() const; + + bool has_species(const Species &sp) const + { + return num_voxels_exact(sp) != 0; + } + + virtual Integer num_molecules(const Species &sp) const; + + virtual Integer num_molecules_exact(const Species &sp) const + { + return num_voxels_exact(sp); + } + + /* + * VoxelSpace Traits + */ + Real voxel_radius() const { return voxel_radius_; } + + Real voxel_volume() const { return calculate_voxel_volume(voxel_radius_); } + + Real get_volume(const Species &sp) const + { + return voxel_volume() * num_voxels_exact(sp); + } + + Real unit_area() const + { + const Real r(voxel_radius_); + return 2.0 * sqrt(3.0) * r * r; + } + + std::shared_ptr vacant() { return vacant_; } + + std::shared_ptr vacant() const { return vacant_; } + + boost::optional find_voxel(const ParticleID &pid) const + { + for (const auto &key_value : molecule_pools_) + { + const auto &pool(key_value.second); + + const auto itr(pool->find(pid)); + if (itr != pool->end()) + { + return VoxelView(pid, pool->species(), itr->coordinate); + } + } + return boost::none; + } + + boost::optional get_coordinate(const ParticleID &pid) const + { + for (const auto &key_value : molecule_pools_) + { + const auto &pool(key_value.second); + const auto itr(pool->find(pid)); + if (itr != pool->end()) + return itr->coordinate; + } + return boost::none; + } + + bool has_voxel(const ParticleID &pid) const; + Integer num_voxels_exact(const Species &sp) const; + Integer num_voxels(const Species &sp) const; + Integer num_voxels() const; + + virtual std::vector list_voxels() const; + virtual std::vector list_voxels(const Species &sp) const; + virtual std::vector list_voxels_exact(const Species &sp) const; + + VoxelView get_voxel_at(const coordinate_type &coord) const + { + std::shared_ptr vp(get_voxel_pool_at(coord)); + return VoxelView(vp->get_particle_id(coord), vp->species(), coord); + } + + std::shared_ptr find_voxel_pool(const Species &sp); + std::shared_ptr find_voxel_pool(const Species &sp) const; + + bool has_molecule_pool(const Species &sp) const; + + std::shared_ptr find_molecule_pool(const Species &sp); + std::shared_ptr + find_molecule_pool(const Species &sp) const; + + virtual std::shared_ptr + get_voxel_pool_at(const coordinate_type &coord) const = 0; + + /* + * Coordinate Transformation + */ + virtual Real3 coordinate2position(const coordinate_type &coord) const = 0; + virtual coordinate_type position2coordinate(const Real3 &pos) const = 0; + + /* + * Neighbor + */ + virtual Integer num_neighbors(const coordinate_type &coord) const = 0; + + virtual coordinate_type get_neighbor(const coordinate_type &coord, + const Integer &nrand) const = 0; + + /* + * Voxel Manipulation + */ + virtual bool update_voxel(const ParticleID &pid, const Species &species, + const coordinate_type coordinate) = 0; + virtual bool add_voxel(const Species &species, const ParticleID &pid, + const coordinate_type &coord) = 0; + virtual bool remove_voxel(const ParticleID &pid) = 0; + virtual bool remove_voxel(const coordinate_type &coord) = 0; + + virtual bool can_move(const coordinate_type &src, + const coordinate_type &dest) const = 0; + + virtual bool move(const coordinate_type &src, const coordinate_type &dest, + const std::size_t candidate = 0) = 0; + + virtual Integer size() const = 0; + virtual Integer3 shape() const = 0; + virtual Integer actual_size() const = 0; + + bool make_molecular_type(const Species &sp, const std::string loc); + bool make_structure_type(const Species &sp, const std::string loc); + + virtual bool is_inside(const coordinate_type &coord) const { return true; } + +protected: + Real t_; + Real voxel_radius_; + + std::shared_ptr vacant_; + + voxel_pool_map_type voxel_pools_; + molecule_pool_map_type molecule_pools_; +}; + +} // namespace ecell4 + +#endif /* ECELL4_VOXELSPACEBASE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/ReactionRule.cpp",".cpp","8835","336","#include +#include + +#include ""ReactionRule.hpp"" +#include ""Context.hpp"" + +namespace ecell4 +{ + +ReactionRule::ReactionRule() + : k_(0), reactants_(), products_(), + policy_(POLICY_STRICT), attributes_(), rr_descriptor_() +{ + ; +} + +ReactionRule::ReactionRule( + const reactant_container_type& reactants, + const product_container_type& products) + : k_(0), reactants_(reactants), products_(products), + policy_(POLICY_STRICT), attributes_(), rr_descriptor_() +{ + ; +} + +ReactionRule::ReactionRule( + const reactant_container_type& reactants, + const product_container_type& products, + const Real& k) + : k_(k), reactants_(reactants), products_(products), + policy_(POLICY_STRICT), attributes_(), rr_descriptor_() +{ + ; +} + +ReactionRule::ReactionRule( + const reactant_container_type& reactants, + const product_container_type& products, + const Quantity& k) + : k_(k), reactants_(reactants), products_(products), + policy_(POLICY_STRICT), attributes_(), rr_descriptor_() +{ + ; +} + +ReactionRule::ReactionRule(const ReactionRule& rr) + : k_(rr.k_), reactants_(rr.reactants_), products_(rr.products_), + policy_(rr.policy_), attributes_(rr.attributes_), rr_descriptor_() +{ + if (rr.has_descriptor()) + { + set_descriptor(std::shared_ptr(rr.get_descriptor()->clone())); + } +} + +Real ReactionRule::k() const +{ + return k_.magnitude; +} + +void ReactionRule::set_k(const Real& k) +{ + set_k(Quantity(k)); +} + +void ReactionRule::set_k(const Quantity& k) +{ + if (k.magnitude < 0) + { + throw std::invalid_argument(""a kinetic rate must be positive.""); + } + k_ = k; +} + +Quantity ReactionRule::get_k() const +{ + return k_; +} + +const ReactionRule::reactant_container_type& ReactionRule::reactants() const +{ + return reactants_; +} + +const ReactionRule::product_container_type& ReactionRule::products() const +{ + return products_; +} + +void ReactionRule::add_reactant(const Species& sp) +{ + reactants_.push_back(sp); +} + +void ReactionRule::add_product(const Species& sp) +{ + products_.push_back(sp); +} + +const ReactionRule::policy_type ReactionRule::policy() const +{ + return policy_; +} + +void ReactionRule::set_policy(const ReactionRule::policy_type policy) +{ + policy_ = policy; +} + + +const std::string ReactionRule::as_string() const +{ + std::stringstream oss; + std::vector tmp; + if (!has_descriptor()) + { + for (reactant_container_type::const_iterator i(reactants_.begin()); + i != reactants_.end(); ++i) + { + tmp.push_back((*i).serial()); + } + oss << boost::algorithm::join(tmp, ""+"") << "">""; + tmp.clear(); + for (product_container_type::const_iterator i(products_.begin()); + i != products_.end(); ++i) + { + tmp.push_back((*i).serial()); + } + oss << boost::algorithm::join(tmp, ""+"") << ""|"" << k(); + } + else + { + { + reactant_container_type::const_iterator i(reactants_.begin()); + ReactionRuleDescriptor::coefficient_container_type::const_iterator + j(rr_descriptor_->reactant_coefficients().begin()); + for (; i != reactants_.end() && j != rr_descriptor_->reactant_coefficients().end(); ++i, ++j) + { + std::stringstream oss_; + oss_ << (*j) << ""*"" << (*i).serial(); + tmp.push_back(oss_.str()); + } + oss << boost::algorithm::join(tmp, ""+"") << "">""; + } + tmp.clear(); + { + product_container_type::const_iterator i(products_.begin()); + ReactionRuleDescriptor::coefficient_container_type::const_iterator + j(rr_descriptor_->product_coefficients().begin()); + for (; i != products_.end() && j != rr_descriptor_->product_coefficients().end(); ++i, ++j) + { + std::stringstream oss_; + oss_ << (*j) << ""*"" << (*i).serial(); + tmp.push_back(oss_.str()); + } + oss << boost::algorithm::join(tmp, ""+"") << ""|"" << k(); + } + } + return oss.str(); +} + +Integer ReactionRule::count(const ReactionRule::reactant_container_type& reactants) const +{ + return this->generate(reactants).size(); +} + +std::vector ReactionRule::generate(const reactant_container_type& reactants) const +{ + return generate_reaction_rules(*this, reactants); +} + +bool ReactionRule::has_descriptor() const +{ + return (rr_descriptor_.get() != NULL); +} + +void ReactionRule::set_descriptor(const std::shared_ptr& descriptor) +{ + rr_descriptor_ = descriptor; +} + +const std::shared_ptr& ReactionRule::get_descriptor() const +{ + return rr_descriptor_; +} + +void ReactionRule::reset_descriptor() +{ + std::shared_ptr tmp; + rr_descriptor_.swap(tmp); +} + +ReactionRule format_reaction_rule_with_nosort(const ReactionRule& rr) +{ + ReactionRule::reactant_container_type reactants; + reactants.reserve(rr.reactants().size()); + for (ReactionRule::reactant_container_type::const_iterator i(rr.reactants().begin()); + i != rr.reactants().end(); ++i) + { + reactants.push_back(format_species(*i)); + } + + ReactionRule::product_container_type products; + products.reserve(rr.products().size()); + for (ReactionRule::product_container_type::const_iterator i(rr.products().begin()); + i != rr.products().end(); ++i) + { + products.push_back(format_species(*i)); + } + + return ReactionRule(reactants, products, rr.k()); +} + +ReactionRule format_reaction_rule(const ReactionRule& rr) +{ + ReactionRule::reactant_container_type reactants; + reactants.reserve(rr.reactants().size()); + for (ReactionRule::reactant_container_type::const_iterator i(rr.reactants().begin()); + i != rr.reactants().end(); ++i) + { + reactants.push_back(format_species(*i)); + } + + ReactionRule::product_container_type products; + products.reserve(rr.products().size()); + for (ReactionRule::product_container_type::const_iterator i(rr.products().begin()); + i != rr.products().end(); ++i) + { + products.push_back(format_species(*i)); + } + + std::sort(reactants.begin(), reactants.end()); + std::sort(products.begin(), products.end()); + return ReactionRule(reactants, products, rr.k()); + // ReactionRule::reactant_container_type reactants(rr.reactants()); + // ReactionRule::product_container_type products(rr.products()); + // std::sort(reactants.begin(), reactants.end()); + // std::sort(products.begin(), products.end()); + // return ReactionRule(reactants, products, rr.k()); + // return rr; +} + +ReactionRule::attribute_type ReactionRule::get_attribute(const std::string& key) const +{ + return attributes_.get(key); +} + +std::vector > ReactionRule::list_attributes() const +{ + return attributes_.values(); +} + +void ReactionRule::set_attributes(const Attribute& attr) +{ + attributes_ = attr; +} + +void ReactionRule::remove_attribute(const std::string& key) +{ + attributes_.remove(key); +} + +bool ReactionRule::has_attribute(const std::string& key) const +{ + return attributes_.has_key(key); +} + +const Attribute& ReactionRule::attributes() const +{ + return attributes_; +} + +ReactionRule create_degradation_reaction_rule( + const Species& reactant1, const Real& k) +{ + ReactionRule rr; + rr.set_k(k); + rr.add_reactant(reactant1); + return rr; +} + +ReactionRule create_synthesis_reaction_rule( + const Species& product1, const Real& k) +{ + ReactionRule rr; + rr.set_k(k); + rr.add_product(product1); + return rr; +} + +ReactionRule create_unimolecular_reaction_rule( + const Species& reactant1, const Species& product1, const Real& k) +{ + ReactionRule rr; + rr.set_k(k); + rr.add_reactant(reactant1); + rr.add_product(product1); + return rr; +} + +ReactionRule create_binding_reaction_rule( + const Species& reactant1, const Species& reactant2, const Species& product1, + const Real& k) +{ + ReactionRule rr; + rr.set_k(k); + rr.add_reactant(reactant1); + rr.add_reactant(reactant2); + rr.add_product(product1); + return rr; +} + +ReactionRule create_unbinding_reaction_rule( + const Species& reactant1, const Species& product1, const Species& product2, + const Real& k) +{ + ReactionRule rr; + rr.set_k(k); + rr.add_reactant(reactant1); + rr.add_product(product1); + rr.add_product(product2); + return rr; +} + +// ReactionRule create_repulsive_reaction_rule( +// const Species& reactant1, const Species& reactant2) +// { +// ReactionRule rr; +// rr.set_k(0.0); +// rr.add_reactant(reactant1); +// rr.add_reactant(reactant2); +// return rr; +// } + +}// ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/VoxelView.hpp",".hpp","488","29","#ifndef ECELL4_VOXELVIEW_HPP +#define ECELL4_VOXELVIEW_HPP + +#include ""Identifier.hpp"" +#include ""Species.hpp"" +#include ""types.hpp"" + +namespace ecell4 +{ + +template +struct ParticleBase +{ + ParticleID pid; + const Species &species; + T voxel; + + ParticleBase(ParticleID pid, const Species &species, T voxel) + : pid(pid), species(species), voxel(voxel) + { + } +}; + +using VoxelView = ParticleBase; + +} // namespace ecell4 + +#endif /* ECELL4_VOXELVIEW_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/HCPLatticeSpace.hpp",".hpp","5985","199","#ifndef ECELL4_HCP_LATTICE_SPACE_HPP +#define ECELL4_HCP_LATTICE_SPACE_HPP + +#include ""VoxelSpaceBase.hpp"" + +namespace ecell4 +{ + +class HCPLatticeSpace : public VoxelSpaceBase +{ +public: + typedef VoxelSpaceBase base_type; + +public: + HCPLatticeSpace(const Real3 &edge_lengths, const Real &voxel_radius, + const bool is_periodic) + : base_type(voxel_radius) + { + set_lattice_properties(edge_lengths, is_periodic); + } + + virtual ~HCPLatticeSpace() + { + ; // do nothing + } + + virtual void reset(const Real3 &edge_lengths, const Real &voxel_radius, + const bool is_periodic) + { + voxel_radius_ = voxel_radius; + + set_lattice_properties(edge_lengths, is_periodic); + } + + void set_lattice_properties(const Real3 &edge_lengths, + const bool is_periodic); + + /** + * Primitives + */ + + const Real3 &edge_lengths() const { return edge_lengths_; } + + virtual const Integer col_size() const { return col_size_ - 2; } + + virtual const Integer row_size() const { return row_size_ - 2; } + + virtual const Integer layer_size() const { return layer_size_ - 2; } + + /** + Coordinate transformations + */ + coordinate_type global2coordinate(const Integer3 &global) const + { + const Integer3 g(global.col + 1, global.row + 1, global.layer + 1); + return g.row + row_size_ * (g.col + col_size_ * g.layer); + } + + Integer3 coordinate2global(const coordinate_type &coord) const + { + const Integer NUM_COLROW(row_size_ * col_size_); + const Integer LAYER(coord / NUM_COLROW); + const Integer SURPLUS(coord - LAYER * NUM_COLROW); + const Integer COL(SURPLUS / row_size_); + const Integer3 global(COL, SURPLUS - COL * row_size_, LAYER); + const Integer3 retval(global.col - 1, global.row - 1, global.layer - 1); + return retval; + } + + Real3 coordinate2position(const coordinate_type &coord) const + { + return global2position(coordinate2global(coord)); + } + + coordinate_type position2coordinate(const Real3 &pos) const + { + return global2coordinate(position2global(pos)); + } + + Real3 global2position(const Integer3 &global) const + { + // the center point of a voxel + const Real3 pos( + global.col * HCP_X, (global.col % 2) * HCP_L + HCP_Y * global.layer, + (global.row * 2 + (global.layer + global.col) % 2) * voxel_radius_); + return pos; + } + + Integer3 position2global(const Real3 &pos) const + { + const Integer col(round(pos[0] / HCP_X)); + const Integer layer(round((pos[1] - (col % 2) * HCP_L) / HCP_Y)); + const Integer row( + round((pos[2] / voxel_radius_ - ((layer + col) % 2)) / 2)); + const Integer3 global(col, row, layer); + return global; + } + + Integer num_neighbors(const coordinate_type &coord) const + { + if (!is_inside(coord)) + return 0; + return 12; + } + + coordinate_type periodic_transpose(const coordinate_type &coord) const + { + Integer3 global(coordinate2global(coord)); + + global.col = global.col % col_size(); + global.row = global.row % row_size(); + global.layer = global.layer % layer_size(); + + global.col = global.col < 0 ? global.col + col_size() : global.col; + global.row = global.row < 0 ? global.row + row_size() : global.row; + global.layer = + global.layer < 0 ? global.layer + layer_size() : global.layer; + + return global2coordinate(global); + } + +protected: + coordinate_type get_neighbor_(const coordinate_type &coord, + const Integer &nrand) const + { + const Integer NUM_COLROW(col_size_ * row_size_); + const Integer NUM_ROW(row_size_); + const bool odd_col(((coord % NUM_COLROW) / NUM_ROW) & 1); + const bool odd_lay((coord / NUM_COLROW) & 1); + + if (!is_inside(coord)) + throw NotFound(""There is no neighbor voxel.""); + + switch (nrand) + { + case 0: + return coord - 1; + case 1: + return coord + 1; + case 2: + return coord + (odd_col ^ odd_lay) - NUM_ROW - 1; + case 3: + return coord + (odd_col ^ odd_lay) - NUM_ROW; + case 4: + return coord + (odd_col ^ odd_lay) + NUM_ROW - 1; + case 5: + return coord + (odd_col ^ odd_lay) + NUM_ROW; + case 6: + return coord - (2 * odd_col - 1) * NUM_COLROW - NUM_ROW; + case 7: + return coord - (2 * odd_col - 1) * NUM_COLROW + NUM_ROW; + case 8: + return coord + (odd_col ^ odd_lay) - NUM_COLROW - 1; + case 9: + return coord + (odd_col ^ odd_lay) - NUM_COLROW; + case 10: + return coord + (odd_col ^ odd_lay) + NUM_COLROW - 1; + case 11: + return coord + (odd_col ^ odd_lay) + NUM_COLROW; + } + throw NotFound(""Invalid argument: nrand""); + } + +public: + bool is_in_range(const coordinate_type &coord) const + { + return coord >= 0 && coord < row_size_ * col_size_ * layer_size_; + } + + virtual bool is_inside(const coordinate_type &coord) const + { + const Integer3 global(coordinate2global(coord)); + return global.col >= 0 && global.col < col_size() && global.row >= 0 && + global.row < row_size() && global.layer >= 0 && + global.layer < layer_size(); + } + + virtual Integer size() const { return row_size_ * col_size_ * layer_size_; } + + virtual Integer3 shape() const + { + return Integer3(col_size_, row_size_, layer_size_); + } + + virtual Integer actual_size() const + { + return col_size() * row_size() * layer_size(); + } + +protected: + Real3 edge_lengths_; + Real HCP_L, HCP_X, HCP_Y; + Integer row_size_, layer_size_, col_size_; +}; + +} // namespace ecell4 + +#endif /* ECELL4_LATTICE_SPACE_BASE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/extras.hpp",".hpp","3613","132","#ifndef ECELL4_EXTRAS_HPP +#define ECELL4_EXTRAS_HPP + +#include +#include + +#ifdef WITH_HDF5 +#include +#include +#endif + +#include ""types.hpp"" +#include ""Real3.hpp"" +#include ""Species.hpp"" +#include ""Particle.hpp"" +#include ""AABB.hpp"" +#include ""Model.hpp"" +#include ""Shape.hpp"" + + +namespace ecell4 +{ + +namespace extras +{ + +template +void throw_in_particles( + Tworld_& world, const Species& sp, const Integer& N, + const std::shared_ptr shape, + std::shared_ptr& rng) +{ + typedef typename Tworld_::molecule_info_type molecule_info_type; + std::shared_ptr + myrng(static_cast >(rng)); + + if (N < 0) + { + throw std::invalid_argument(""the number of particles must be positive.""); + } + + // const Real3 edge_lengths(world.edge_lengths()); + const molecule_info_type info(world.get_molecule_info(sp)); + + for (int i(0); i < N; ++i) + { + while (true) + { + // const Real3 pos( + // rng.uniform(0.0, edge_lengths[0]), + // rng.uniform(0.0, edge_lengths[1]), + // rng.uniform(0.0, edge_lengths[2])); + // if (world.list_particles_within_radius(pos, info.radius).size() + // == 0) + // { + // world.new_particle(Particle(sp, pos, info.radius, info.D)); + // break; + // } + const Real3 pos(shape->draw_position(myrng)); + if (world.new_particle(Particle(sp, pos, info.radius, info.D)).second) + { + break; + } + } + } +} + +template +void throw_in_particles( + Tworld_& world, const Species& sp, const Integer& N, std::shared_ptr& rng) +{ + std::shared_ptr shape(new AABB(Real3(0, 0, 0), world.edge_lengths())); + throw_in_particles(world, sp, N, shape, rng); +} + +template +typename Tfactory_::world_type* generate_world_from_model( + const Tfactory_& f, const std::shared_ptr& m) +{ + typename Tfactory_::world_type* w = f.world(); + w->bind_to(m); + return w; +} + +Shape::dimension_kind +get_dimension_from_model(const Species& species, const std::shared_ptr& model); + +struct VersionInformation +{ + typedef enum PreRelease + { + NONE = 0, + ALPHA = 1, + BETA = 2, + RC = 3, + FINAL = 4 + } prerelease_type; + + std::string header; + unsigned int majorno, minorno, patchno; + prerelease_type pre; + unsigned int preno; + int devno; + + VersionInformation( + const std::string& header, const unsigned int majorno, const unsigned int minorno, const unsigned int patchno, + const prerelease_type pre, const unsigned int preno, const int devno) + : header(header), majorno(majorno), minorno(minorno), patchno(patchno), + pre(pre), preno(preno), devno(devno) + { + ; + } +}; + +VersionInformation parse_version_information(const std::string& version); +bool check_version_information(const std::string& version, const std::string& required); + +#ifdef WITH_HDF5 +void save_version_information(H5::H5Location* root, const std::string& version); +std::string load_version_information(const H5::H5Location& root); +#endif +std::string load_version_information(const std::string& filename); + +std::vector > get_stoichiometry( + const std::vector& species_list, const std::vector& reaction_rules); + +} // extras + +} // ecell4 + +#endif // ECELL4_EXTRAS_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/SubvolumeSpace.hpp",".hpp","16941","594","#ifndef ECELL4_SUBVOLUME_SPACE_HPP +#define ECELL4_SUBVOLUME_SPACE_HPP + +#include ""types.hpp"" +#include ""exceptions.hpp"" +#include ""Species.hpp"" +// #include ""Space.hpp"" +#include ""Integer3.hpp"" +#include ""Shape.hpp"" +#include + +#ifdef WITH_HDF5 +#include ""SubvolumeSpaceHDF5Writer.hpp"" +#endif + + +namespace ecell4 +{ + +class SubvolumeSpace + // : public Space +{ +public: + + typedef Integer coordinate_type; + +public: + + class PoolBase + { + public: + + PoolBase(const Species& sp, const Real D, const Species::serial_type& loc) + : sp_(sp), D_(D), loc_(loc) + { + ; + } + + virtual ~PoolBase() + { + ; + } + + const Species& species() const + { + return sp_; + } + + const Real D() const + { + return D_; + } + + const Species::serial_type& loc() const + { + return loc_; + } + + virtual coordinate_type size() const = 0; + virtual Integer num_molecules(const coordinate_type& i) const = 0; + virtual Integer num_molecules() const = 0; + virtual void add_molecules(const Integer num, const coordinate_type& i) = 0; + virtual void remove_molecules(const Integer num, const coordinate_type& i) = 0; + virtual std::vector list_coordinates() const = 0; + virtual const std::vector get_data() const = 0; + + protected: + + Species sp_; + Real D_; + Species::serial_type loc_; + }; + +public: + + SubvolumeSpace() + : t_(0.0) + { + } + + virtual ~SubvolumeSpace() + { + ; + } + + // SpaceTraits + + const Real t() const + { + return t_; + } + + void set_t(const Real& t) + { + if (t < 0.0) + { + throw std::invalid_argument(""the time must be positive.""); + } + t_ = t; + } + + /** + * get the axes lengths of a cuboidal region. + * @return edge lengths Real3 + */ + virtual const Real3& edge_lengths() const + { + throw NotSupported( + ""edge_lengths() is not supported by this space class""); + } + + /** + * get volume. + * @return a volume (m^3) Real + */ + virtual const Real volume() const + { + throw NotSupported(""volume() is not supported by this space class""); + } + + virtual Integer num_molecules(const Species& sp) const + { + return num_molecules_exact(sp); + } + + virtual Integer num_molecules_exact(const Species& sp) const + { + throw NotImplemented(""num_molecules_exact(const Species&) not implemented""); + } + + virtual Real get_value(const Species& sp) const + { + return static_cast(num_molecules(sp)); + } + + virtual Real get_value_exact(const Species& sp) const + { + return static_cast(num_molecules_exact(sp)); + } + + virtual const Integer3 matrix_sizes() const = 0; + virtual const Real3 subvolume_edge_lengths() const = 0; + virtual const Integer num_subvolumes() const = 0; + virtual const Integer num_subvolumes(const Species& sp) const = 0; + virtual const Real subvolume() const = 0; + + virtual coordinate_type global2coord(const Integer3& g) const = 0; + virtual Integer3 coord2global(const coordinate_type& c) const = 0; + virtual Integer3 position2global(const Real3& pos) const = 0; + + inline Integer position2coordinate(const Real3& pos) const + { + return global2coord(position2global(pos)); + } + + virtual Integer num_molecules( + const Species& sp, const coordinate_type& c) const = 0; + virtual Integer num_molecules_exact( + const Species& sp, const coordinate_type& c) const = 0; + virtual void add_molecules( + const Species& sp, const Integer& num, const coordinate_type& c) = 0; + virtual void remove_molecules( + const Species& sp, const Integer& num, const coordinate_type& c) = 0; + + virtual bool has_species(const Species& sp) const = 0; + virtual const std::vector& species() const = 0; + virtual std::vector list_species() const = 0; + virtual coordinate_type get_neighbor( + const coordinate_type& c, const Integer rnd) const = 0; + + virtual Integer num_molecules(const Species& sp, const Integer3& g) const + { + return num_molecules(sp, global2coord(g)); + } + + virtual Integer num_molecules_exact(const Species& sp, const Integer3& g) const + { + return num_molecules_exact(sp, global2coord(g)); + } + + virtual std::vector list_coordinates(const Species& sp) const = 0; + virtual std::vector list_coordinates_exact(const Species& sp) const = 0; + + virtual void add_structure( + const Species& sp, const std::shared_ptr& shape) = 0; + virtual bool check_structure( + const Species::serial_type& serial, const coordinate_type& coord) const = 0; + virtual Real get_volume(const Species& sp) const = 0; + virtual std::vector list_structures() const = 0; + virtual void update_structure( + const Species::serial_type& serial, const coordinate_type& coord, + const Real& value) = 0; + virtual bool has_structure(const Species& sp) const = 0; + + virtual Real get_occupancy(const Species::serial_type& serial, const coordinate_type& coord) const = 0; + + inline Real get_occupancy(const Species& sp, const coordinate_type& coord) const + { + return get_occupancy(sp.serial(), coord); + } + + inline Real get_occupancy(const Species& sp, const Integer3& g) const + { + return get_occupancy(sp.serial(), global2coord(g)); + } + + // virtual Shape::dimension_kind get_dimension(const Species::serial_type& serial) const = 0; + // inline Shape::dimension_kind get_dimension(const Species& sp) const + // { + // return get_dimension(sp.serial()); + // } + + // virtual void set_dimension( + // const Species::serial_type& serial, const Shape::dimension_kind& ndim); + + inline bool check_structure(const Species::serial_type& serial, const Integer3& g) const + { + return check_structure(serial, global2coord(g)); + } + + inline bool check_structure(const Species& sp, const Integer3& g) const + { + return check_structure(sp.serial(), g); + } + + virtual void reset(const Real3& edge_lengths, const Integer3& matrix_sizes) = 0; + + virtual void save(const std::string& filename) const + { + throw NotSupported( + ""save(const std::string) is not supported by this space class""); + } + +#ifdef WITH_HDF5 + virtual void save_hdf5(H5::Group* root) const = 0; + virtual void load_hdf5(const H5::Group& root) = 0; +#endif + + virtual const std::shared_ptr& get_pool(const Species& sp) const = 0; + virtual const std::shared_ptr reserve_pool(const Species& sp, const Real D, const Species::serial_type& loc) = 0; + + virtual std::vector get_data(const Species& sp) const = 0; + +protected: + + double t_; +}; + +class SubvolumeSpaceVectorImpl + : public SubvolumeSpace +{ +public: + + typedef SubvolumeSpace base_type; + typedef base_type::coordinate_type coordinate_type; + +public: + + typedef base_type::PoolBase PoolBase; + + class Pool + : public PoolBase + { + public: + + typedef PoolBase base_type; + typedef std::vector container_type; + + public: + + Pool(const Species& sp, const Real D, const Species::serial_type& loc, + const container_type::size_type n) + : base_type(sp, D, loc), data_(n, 0) + { + ; + } + + coordinate_type size() const + { + return data_.size(); + } + + Integer num_molecules() const + { + return std::accumulate(data_.begin(), data_.end(), 0); + } + + Integer num_molecules(const coordinate_type& i) const + { + return data_.at(i); + } + + void add_molecules(const Integer num, const coordinate_type& i) + { + data_[i] += num; + } + + void remove_molecules(const Integer num, const coordinate_type& i) + { + data_[i] -= num; + } + + std::vector list_coordinates() const + { + std::vector coords; + for (container_type::size_type i(0); i < data_.size(); ++i) + { + if (data_[i] > 0) + { + coords.resize(coords.size() + data_[i], i); + } + } + return coords; + } + + const std::vector get_data() const + { + return data_; + } + + protected: + + container_type data_; + }; + +public: + + // typedef std::vector cell_type; + // typedef std::unordered_map matrix_type; + typedef std::unordered_map> matrix_type; + + // typedef std::unordered_map structure_container_type; + typedef std::vector structure_cell_type; + typedef std::unordered_map structure_matrix_type; + +public: + + SubvolumeSpaceVectorImpl( + const Real3& edge_lengths, const Integer3 matrix_sizes) + : base_type() + { + matrix_sizes_[0] = matrix_sizes.col; + matrix_sizes_[1] = matrix_sizes.row; + matrix_sizes_[2] = matrix_sizes.layer; + + reset(edge_lengths); + } + + virtual ~SubvolumeSpaceVectorImpl() + { + ; + } + + const Real3& edge_lengths() const + { + return edge_lengths_; + } + + const Integer3 matrix_sizes() const + { + return Integer3(matrix_sizes_[0], matrix_sizes_[1], matrix_sizes_[2]); + } + + const Real3 subvolume_edge_lengths() const + { + return Real3( + edge_lengths_[0] / matrix_sizes_[0], + edge_lengths_[1] / matrix_sizes_[1], + edge_lengths_[2] / matrix_sizes_[2]); + } + + const Real volume() const + { + return edge_lengths_[0] * edge_lengths_[1] * edge_lengths_[2]; + } + + const Integer num_subvolumes() const + { + return matrix_sizes_[0] * matrix_sizes_[1] * matrix_sizes_[2]; + } + + const Integer num_subvolumes(const Species& sp) const; + + const Real subvolume() const + { + return volume() / num_subvolumes(); + } + + coordinate_type global2coord(const Integer3& g) const + { + const coordinate_type coord( + modulo(g.col, matrix_sizes_[0]) + + matrix_sizes_[0] * (modulo(g.row, matrix_sizes_[1]) + + matrix_sizes_[1] * modulo(g.layer, matrix_sizes_[2]))); + return coord; + } + + Integer3 coord2global(const coordinate_type& c) const + { + const Integer rowcol(matrix_sizes_[0] * matrix_sizes_[1]); + const Integer layer(static_cast(c / rowcol)); + const Integer surplus(c - layer * rowcol); + const Integer row(static_cast(surplus / matrix_sizes_[0])); + return Integer3(surplus - row * matrix_sizes_[0], row, layer); + } + + Integer3 position2global(const Real3& pos) const + { + return Integer3( + static_cast(floor(pos[0] * matrix_sizes_[0] / edge_lengths_[0])), + static_cast(floor(pos[1] * matrix_sizes_[1] / edge_lengths_[1])), + static_cast(floor(pos[2] * matrix_sizes_[2] / edge_lengths_[2]))); + } + + Real3 coord2position(const coordinate_type& c) const + { + const Real3 lengths(subvolume_edge_lengths()); + const Integer3 g(coord2global(c)); + const Real3 center( + lengths[0] * (g[0] + 0.5), + lengths[1] * (g[1] + 0.5), + lengths[2] * (g[2] + 0.5)); + return center; + } + + Integer num_molecules(const Species& sp) const; + Integer num_molecules_exact(const Species& sp) const; + + Integer num_molecules(const Species& sp, const coordinate_type& c) const; + Integer num_molecules_exact(const Species& sp, const coordinate_type& c) const; + void add_molecules(const Species& sp, const Integer& num, const coordinate_type& c); + void remove_molecules(const Species& sp, const Integer& num, const coordinate_type& c); + + std::vector list_coordinates(const Species& sp) const; + std::vector list_coordinates_exact(const Species& sp) const; + + void add_structure(const Species& sp, const std::shared_ptr& shape); + bool check_structure(const Species::serial_type& serial, const coordinate_type& coord) const; + Real get_volume(const Species& sp) const; + std::vector list_structures() const; + + void update_structure( + const Species::serial_type& serial, const coordinate_type& coord, + const Real& value); + + bool has_structure(const Species& sp) const + { + structure_matrix_type::const_iterator i(structure_matrix_.find(sp.serial())); + if (i == structure_matrix_.end()) + { + return false; + } + for (structure_cell_type::const_iterator j((*i).second.begin()); + j != (*i).second.end(); ++j) + { + if ((*j) > 0) + { + return true; + } + } + return false; + } + + inline Real unit_area() const + { + const Real3 l(subvolume_edge_lengths()); + return (l[0] * l[1] + l[0] * l[2] + l[1] * l[2]) / (3 * l[0] * l[1] * l[2]); + } + + Real get_occupancy(const Species::serial_type& serial, const coordinate_type& coord) const + { + structure_matrix_type::const_iterator i(structure_matrix_.find(serial)); + if (i == structure_matrix_.end()) + { + return 0.0; + } + return (*i).second[coord]; + } + + // Shape::dimension_kind get_dimension(const Species::serial_type& serial) const + // { + // structure_container_type::const_iterator i(structures_.find(serial)); + // if (i == structures_.end()) + // { + // throw NotFound(""No correspoinding structure was found.""); + // } + // return (*i).second; + // } + + // void set_dimension( + // const Species::serial_type& serial, const Shape::dimension_kind& ndim) + // { + // structure_container_type::iterator i(structures_.find(serial)); + // if (i == structures_.end()) + // { + // throw NotFound(""No correspoinding structure was found.""); + // } + // else + // { + // (*i).second = ndim; + // } + // } + + coordinate_type get_neighbor(const coordinate_type& c, const Integer rnd) const; + + virtual bool has_species(const Species& sp) const + { + return matrix_.find(sp) != matrix_.end(); + } + + const std::vector& species() const + { + return species_; + } + + std::vector list_species() const + { + // std::vector retval; + // for (matrix_type::const_iterator i(matrix_.begin()); i != matrix_.end(); ++i) + // { + // retval.push_back((*i).first); + // } + // return retval; + return species_; + } + +#ifdef WITH_HDF5 + void save_hdf5(H5::Group* root) const + { + save_subvolume_space(*this, root); + } + + void load_hdf5(const H5::Group& root) + { + load_subvolume_space(root, this); + } +#endif + + void reset(const Real3& edge_lengths) + { + reset(edge_lengths, matrix_sizes()); + } + + void reset(const Real3& edge_lengths, const Integer3& matrix_sizes) + { + base_type::t_ = 0.0; + matrix_.clear(); + species_.clear(); + + for (Real3::size_type dim(0); dim < 3; ++dim) + { + if (edge_lengths[dim] <= 0) + { + throw std::invalid_argument(""the edge length must be positive.""); + } + } + + edge_lengths_ = edge_lengths; + + matrix_sizes_[0] = matrix_sizes.col; + matrix_sizes_[1] = matrix_sizes.row; + matrix_sizes_[2] = matrix_sizes.layer; + } + + const std::shared_ptr& get_pool(const Species& sp) const; + const std::shared_ptr reserve_pool( + const Species& sp, const Real D, const Species::serial_type& loc); + + virtual std::vector get_data(const Species& sp) const + { + return get_pool(sp)->get_data(); + } + +protected: + + void add_structure3(const Species& sp, const std::shared_ptr& shape); + void add_structure2(const Species& sp, const std::shared_ptr& shape); + bool is_surface_subvolume(const coordinate_type& c, const std::shared_ptr& shape); + +protected: + + Real3 edge_lengths_; + std::array matrix_sizes_; + matrix_type matrix_; + std::vector species_; + + // structure_container_type structures_; + structure_matrix_type structure_matrix_; +}; + +} // ecell4 + +#endif /* ECELL4_SUBVOLUME_SPACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/CompartmentSpaceHDF5Writer.hpp",".hpp","9025","255","#ifndef ECELL4_COMPARTMENT_SPACE_HDF5_WRITER_HPP +#define ECELL4_COMPARTMENT_SPACE_HDF5_WRITER_HPP + +#include +#include +#include + +#include +#include + +#include ""types.hpp"" +#include ""Species.hpp"" +#include ""Real3.hpp"" +#include ""Space.hpp"" // just for Space::space_kind + + +namespace ecell4 +{ + +struct H5DataTypeTraits_uint32_t +{ + typedef uint32_t type; + + static const H5::DataType& get() + { + return H5::PredType::STD_I32LE; + } +}; + +struct H5DataTypeTraits_double +{ + typedef double type; + + static const H5::DataType& get() + { + return H5::PredType::IEEE_F64LE; + } +}; + +template +struct CompartmentSpaceHDF5TraitsBase +{ + typedef Tspace_ space_type; + typedef Tdata_ num_molecules_traits_type; + typedef typename num_molecules_traits_type::type num_molecules_type; + + typedef struct species_id_table_struct { + uint32_t sid; + char serial[32]; // species' serial may exceed the limit + } species_id_table_struct; + + static H5::CompType get_species_id_table_struct_memtype() + { + H5::CompType mtype_id_table_struct(sizeof(species_id_table_struct)); + // const H5std_string name1(""sid""); + // const H5std_string name2(""serial""); + // mtype_id_table_struct.insertMember( + // name1, HOFFSET(species_id_table_struct, sid), + // H5::PredType::STD_I32LE); + // mtype_id_table_struct.insertMember( + // name2, HOFFSET(species_id_table_struct, serial), + // H5::StrType(H5::PredType::C_S1, 32)); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(mtype_id_table_struct.getId(), #member,\ + HOFFSET(species_id_table_struct, member), type.getId()) + INSERT_MEMBER(sid, H5::PredType::STD_I32LE); + INSERT_MEMBER(serial, H5::StrType(H5::PredType::C_S1, 32)); +#undef INSERT_MEMBER + return mtype_id_table_struct; + } + + typedef struct species_num_struct { + uint32_t sid; + num_molecules_type num_molecules; + } species_num_struct; + + static H5::CompType get_species_num_struct_memtype() + { + H5::CompType mtype_num_struct(sizeof(species_num_struct)); + // const H5std_string name1(""sid""); + // const H5std_string name2(""num_molecules""); + // mtype_num_struct.insertMember( + // name1, HOFFSET(species_num_struct, sid), + // H5::PredType::STD_I32LE); + // mtype_num_struct.insertMember( + // name2, + // HOFFSET(species_num_struct, num_molecules), + // num_molecules_traits_type::get()); +#define INSERT_MEMBER(member, type) \ + H5Tinsert(mtype_num_struct.getId(), #member,\ + HOFFSET(species_num_struct, member), type.getId()) + INSERT_MEMBER(sid, H5::PredType::STD_I32LE); + INSERT_MEMBER(num_molecules, num_molecules_traits_type::get()); +#undef INSERT_MEMBER + return mtype_num_struct; + } + + virtual num_molecules_type getter( + const space_type& space, const Species& sp) const = 0; + virtual void setter( + space_type& space, const Species& sp, const num_molecules_type& value) const = 0; +}; + +template +struct CompartmentSpaceHDF5Traits + : public CompartmentSpaceHDF5TraitsBase +{ + typedef CompartmentSpaceHDF5TraitsBase base_type; + typedef typename base_type::num_molecules_type num_molecules_type; + typedef typename base_type::space_type space_type; + + num_molecules_type getter(const space_type& space, const Species& sp) const + { + return space.num_molecules_exact(sp); + } + + void setter( + Tspace_& space, const Species& sp, const num_molecules_type& value) const + { + space.add_molecules(sp, value); + } +}; + +// template +template +void save_compartment_space(const typename Ttraits_::space_type& space, H5::Group* root) +{ + // typedef CompartmentSpaceHDF5Traits traits_type; + typedef Ttraits_ traits_type; + typedef typename traits_type::species_id_table_struct species_id_table_struct; + typedef typename traits_type::species_num_struct species_num_struct; + + // attributes + const uint32_t space_type = static_cast(Space::COMPARTMENT); + H5::Attribute attr_space_type( + root->createAttribute( + ""type"", H5::PredType::STD_I32LE, H5::DataSpace(H5S_SCALAR))); + attr_space_type.write(H5::PredType::STD_I32LE, &space_type); + + const double t(space.t()); + H5::Attribute attr_t(root->createAttribute( + ""t"", H5DataTypeTraits_double::get(), H5::DataSpace(H5S_SCALAR))); + attr_t.write(attr_t.getDataType(), &t); + + const double volume(space.volume()); + H5::Attribute attr_volume(root->createAttribute( + ""volume"", H5DataTypeTraits_double::get(), H5::DataSpace(H5S_SCALAR))); + attr_volume.write(attr_volume.getDataType(), &volume); + + const std::vector species_list(space.list_species()); + const std::vector::size_type num_species(species_list.size()); + + std::unique_ptr + species_id_table(new species_id_table_struct[num_species]); + std::unique_ptr + species_num_table(new species_num_struct[num_species]); + + for(unsigned int i(0); i < num_species; ++i) + { + species_id_table[i].sid = i + 1; + std::strcpy( + species_id_table[i].serial, species_list[i].serial().c_str()); + + species_num_table[i].sid = i + 1; + species_num_table[i].num_molecules = + space.num_molecules(species_list[i]); + } + + const int RANK = 1; + hsize_t dim[1]; + dim[0] = num_species; + H5::DataSpace dataspace(RANK, dim); + + std::unique_ptr dataset_id_table(new H5::DataSet( + root->createDataSet( + ""species"", traits_type::get_species_id_table_struct_memtype(), + dataspace))); + std::unique_ptr dataset_num_table(new H5::DataSet( + root->createDataSet( + ""num_molecules"", traits_type::get_species_num_struct_memtype(), + dataspace))); + dataset_id_table->write( + species_id_table.get(), dataset_id_table->getDataType()); + dataset_num_table->write( + species_num_table.get(), dataset_num_table->getDataType()); + + const Real3 edge_lengths = space.edge_lengths(); + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + H5::Attribute attr_lengths( + root->createAttribute( + ""edge_lengths"", lengths_type, H5::DataSpace(H5S_SCALAR))); + double lengths[] = {edge_lengths[0], edge_lengths[1], edge_lengths[2]}; + attr_lengths.write(lengths_type, lengths); +} + +// template +template +void load_compartment_space(const H5::Group& root, typename Ttraits_::space_type* space) +{ + // typedef CompartmentSpaceHDF5Traits traits_type; + typedef Ttraits_ traits_type; + typedef typename traits_type::num_molecules_type num_molecules_type; + typedef typename traits_type::species_id_table_struct species_id_table_struct; + typedef typename traits_type::species_num_struct species_num_struct; + + Real3 edge_lengths; + const hsize_t dims[] = {3}; + const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims); + root.openAttribute(""edge_lengths"").read(lengths_type, &edge_lengths); + space->reset(edge_lengths); + + double t; + root.openAttribute(""t"").read(H5DataTypeTraits_double::get(), &t); + space->set_t(t); + + { + H5::DataSet species_dset(root.openDataSet(""species"")); + const unsigned int num_species( + species_dset.getSpace().getSimpleExtentNpoints()); + std::unique_ptr species_id_table( + new species_id_table_struct[num_species]); + species_dset.read( + species_id_table.get(), + traits_type::get_species_id_table_struct_memtype()); + species_dset.close(); + + H5::DataSet num_dset(root.openDataSet(""num_molecules"")); + std::unique_ptr species_num_table( + new species_num_struct[num_species]); + num_dset.read( + species_num_table.get(), + traits_type::get_species_num_struct_memtype()); + num_dset.close(); + + typename std::unordered_map + num_molecules_cache; + for (unsigned int i(0); i < num_species; ++i) + { + num_molecules_cache[species_num_table[i].sid] + = species_num_table[i].num_molecules; + } + for (unsigned int i(0); i < num_species; ++i) + { + space->add_molecules( + Species(species_id_table[i].serial), + num_molecules_cache[species_id_table[i].sid]); + } + } +} + +} // ecell4 + +#endif /* ECELL4_COMPARTMENT_SPACE_HDF5_WRITER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/observers.hpp",".hpp","32975","1416","#ifndef ECELL4_OBSERVER_HPP +#define ECELL4_OBSERVER_HPP + +#include + +#include ""types.hpp"" +#include ""functions.hpp"" +#include ""Space.hpp"" +#include ""Species.hpp"" +#include ""Real3.hpp"" +#include ""Model.hpp"" +#include ""Simulator.hpp"" +#include ""WorldInterface.hpp"" + +#include +#include + +#include + + +namespace ecell4 +{ + +class Observer +{ +public: + + Observer(const bool e, const Integer num_steps = 0) + : every_(e), num_steps_(num_steps) + { + ; + } + + virtual ~Observer() + { + ; // do nothing + } + + virtual const Real next_time() const; + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual void finalize(const std::shared_ptr& world); + virtual void reset(); + + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + // virtual bool fire(const Simulator* sim, const std::shared_ptr& world) = 0; + + const Integer num_steps() const; + void set_num_steps(const Integer nsteps); + + bool every() + { + return every_; + } + +private: + + const bool every_; + +protected: + + Integer num_steps_; +}; + +class FixedIntervalObserver + : public Observer +{ +public: + + typedef Observer base_type; + +public: + + FixedIntervalObserver(const Real& dt) + : base_type(false), t0_(0.0), dt_(dt), count_(0) + { + ; + } + + FixedIntervalObserver(const Real& dt, const Real& t0, const Integer count) + : base_type(false), t0_(t0), dt_(dt), count_(count) + { + ; + } + + virtual ~FixedIntervalObserver() + { + ; + } + + const Real next_time() const; + + const Real dt() const; + const Real t0() const; + const Integer count() const; + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + +protected: + + Real t0_, dt_; + Integer count_; +}; + +struct NumberLogger +{ + typedef std::vector > data_container_type; + typedef std::vector species_container_type; + + NumberLogger() + : all_species(true) + { + ; + } + + NumberLogger(const std::vector& species) + : all_species(species.size() == 0) + { + targets.reserve(species.size()); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + targets.push_back(Species(*i)); + } + } + + ~NumberLogger() + { + ; + } + + void initialize() + { + ; + } + + void reset() + { + data.clear(); + } + + void log(const std::shared_ptr& world); + void save(const std::string& filename) const; + + species_container_type targets; + data_container_type data; + bool all_species; +}; + +class FixedIntervalNumberObserver + : public FixedIntervalObserver +{ +public: + + typedef FixedIntervalObserver base_type; + +public: + + FixedIntervalNumberObserver(const Real& dt, const std::vector& species) + : base_type(dt), logger_(species) + { + ; + } + + FixedIntervalNumberObserver(const Real& dt) + : base_type(dt), logger_() + { + ; + } + + FixedIntervalNumberObserver(const Real& dt, const Real& t0, const Integer count) + : base_type(dt, t0, count), logger_() + { + ; + } + + virtual ~FixedIntervalNumberObserver() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + NumberLogger::data_container_type data() const; + NumberLogger::species_container_type targets() const; + + const NumberLogger& logger() const + { + return logger_; + } + + void set_logger(const NumberLogger& logger) + { + logger_ = logger; + } + + void save(const std::string& filename) const + { + logger_.save(filename); + } + +protected: + + NumberLogger logger_; +}; + +class NumberObserver + : public Observer +{ +public: + + typedef Observer base_type; + +public: + + NumberObserver(const std::vector& species) + : base_type(true), logger_(species) + { + ; + } + + NumberObserver() + : base_type(true), logger_() + { + ; + } + + virtual ~NumberObserver() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual void finalize(const std::shared_ptr& world); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + NumberLogger::data_container_type data() const; + NumberLogger::species_container_type targets() const; + + const NumberLogger& logger() const + { + return logger_; + } + + void set_logger(const NumberLogger& logger) + { + logger_ = logger; + } + + void save(const std::string& filename) const + { + logger_.save(filename); + } + +protected: + + NumberLogger logger_; +}; + +class TimingObserver + : public Observer +{ +public: + + typedef Observer base_type; + +public: + + TimingObserver(const std::vector& t) + : base_type(false), t_(t), count_(0) + { + ; + } + + TimingObserver(const std::vector& t, const Integer num_steps, const Integer count) + : base_type(false, num_steps), t_(t), count_(count) + { + ; + } + + virtual ~TimingObserver() + { + ; + } + + const Real next_time() const; + + const std::vector& timings() const + { + return t_; + } + + const Integer count() const + { + return count_; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + +protected: + + std::vector t_; + Integer count_; +}; + +class TimingNumberObserver + : public TimingObserver +{ +public: + + typedef TimingObserver base_type; + +public: + + TimingNumberObserver( + const std::vector& t, const std::vector& species) + : base_type(t), logger_(species) + { + ; + } + + TimingNumberObserver(const std::vector& t) + : base_type(t), logger_() + { + ; + } + + TimingNumberObserver(const std::vector& t, const Integer num_steps, const Integer count) + : base_type(t, num_steps, count), logger_() + { + ; + } + + virtual ~TimingNumberObserver() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + NumberLogger::data_container_type data() const; + NumberLogger::species_container_type targets() const; + + const NumberLogger& logger() const + { + return logger_; + } + + void set_logger(const NumberLogger& logger) + { + logger_ = logger; + } + + void save(const std::string& filename) const + { + logger_.save(filename); + } + +protected: + + NumberLogger logger_; +}; + +class FixedIntervalHDF5Observer + : public FixedIntervalObserver +{ +public: + + typedef FixedIntervalObserver base_type; + +public: + + FixedIntervalHDF5Observer(const Real& dt, const std::string& filename) + : base_type(dt), prefix_(filename) + { + ; + } + + FixedIntervalHDF5Observer(const Real& dt, const Real& t0, const Integer count, const std::string& filename) + : base_type(dt, t0, count), prefix_(filename) + { + ; + } + + virtual ~FixedIntervalHDF5Observer() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + + inline const std::string filename() const + { + return filename(num_steps()); + } + + const std::string filename(const Integer idx) const; + + const std::string& prefix() const + { + return prefix_; + } + +protected: + + std::string prefix_; +}; + +struct PositionLogger +{ + typedef std::vector > + particle_container_type; + typedef std::unordered_map + serial_map_type; + + PositionLogger(const std::vector& species) + : species(species), header(""x,y,z,r,sid""), formatter(""%2%,%3%,%4%,%5%,%8%""), serials() + { + ; + } + + PositionLogger() + : species(), header(""x,y,z,r,sid""), formatter(""%2%,%3%,%4%,%5%,%8%""), serials() + { + ; + } + + ~PositionLogger() + { + ; + } + + void initialize() + { + ; + } + + void reset() + { + ; + } + + void write_particles( + std::ofstream& ofs, const Real t, const particle_container_type& particles, + const Species::serial_type label = """") + { + for(particle_container_type::const_iterator i(particles.begin()); + i != particles.end(); ++i) + { + const ParticleID& pid((*i).first); + const Real3 pos((*i).second.position()); + const Real radius((*i).second.radius()); + const Species::serial_type serial( + label == """" ? (*i).second.species_serial() : label); + + unsigned int idx; + serial_map_type::iterator j(serials.find(serial)); + if (j == serials.end()) + { + idx = serials.size(); + serials.insert(std::make_pair(serial, idx)); + } + else + { + idx = (*j).second; + } + + boost::format fmt(formatter); + ofs << (fmt % t % pos[0] % pos[1] % pos[2] % radius + % pid.lot() % pid.serial() % idx).str() << std::endl; + } + } + + void save(std::ofstream& ofs, const std::shared_ptr& world) + { + ofs << std::setprecision(17); + + if (header.size() > 0) + { + ofs << header << std::endl; + } + + if (species.size() == 0) + { + const particle_container_type particles(world->list_particles()); + write_particles(ofs, world->t(), particles); + } + else + { + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Species sp(*i); + const particle_container_type particles(world->list_particles(sp)); + write_particles(ofs, world->t(), particles, *i); + } + } + } + + std::vector species; + std::string header, formatter; + serial_map_type serials; +}; + +class FixedIntervalCSVObserver + : public FixedIntervalObserver +{ +public: + + typedef FixedIntervalObserver base_type; + + typedef std::vector > + particle_container_type; + typedef std::unordered_map + serial_map_type; + +public: + + FixedIntervalCSVObserver( + const Real& dt, const std::string& filename) + : base_type(dt), prefix_(filename), logger_() + { + ; + } + + FixedIntervalCSVObserver( + const Real& dt, const std::string& filename, + const std::vector& species) + : base_type(dt), prefix_(filename), logger_(species) + { + ; + } + + FixedIntervalCSVObserver( + const Real& dt, const std::string& filename, + const Real& t0, const Integer count) + : base_type(dt, t0, count), prefix_(filename), logger_() + { + ; + } + + virtual ~FixedIntervalCSVObserver() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + void log(const std::shared_ptr& world); + virtual void reset(); + + void set_header(const std::string& header) + { + logger_.header = header; + } + + void set_formatter(const std::string& formatter) + { + logger_.formatter = formatter; + } + + const PositionLogger& logger() const + { + return logger_; + } + + void set_logger(const PositionLogger& logger) + { + logger_ = logger; + } + + const std::string& prefix() const + { + return prefix_; + } + + inline const std::string filename() const + { + return filename(num_steps()); + } + + const std::string filename(const Integer idx) const; + +protected: + + std::string prefix_; + PositionLogger logger_; +}; + +class CSVObserver + : public Observer +{ +public: + + typedef Observer base_type; + + typedef std::vector > + particle_container_type; + typedef std::unordered_map + serial_map_type; + +public: + + CSVObserver( + const std::string& filename) + : base_type(true), prefix_(filename), logger_() + { + ; + } + + CSVObserver( + const std::string& filename, + const std::vector& species) + : base_type(true), prefix_(filename), logger_(species) + { + ; + } + + virtual ~CSVObserver() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + void log(const std::shared_ptr& world); + virtual void reset(); + + void set_header(const std::string& header) + { + logger_.header = header; + } + + void set_formatter(const std::string& formatter) + { + logger_.formatter = formatter; + } + + const PositionLogger& logger() const + { + return logger_; + } + + void set_logger(const PositionLogger& logger) + { + logger_ = logger; + } + + const std::string& prefix() const + { + return prefix_; + } + + inline const std::string filename() const + { + return filename(num_steps()); + } + + const std::string filename(const Integer idx) const; + +protected: + + std::string prefix_; + PositionLogger logger_; +}; + +struct TimingEvent +{ + TimingEvent(const std::vector& times) + : times(times), num_steps(0), count(0) + { + ; + } + + TimingEvent() + : times(), num_steps(0), count(0) + { + ; + } + + virtual ~TimingEvent() + { + ; + } + + void set_times(const std::vector& value) + { + times = value; + } + + const Real next_time() const + { + if (count < times.size()) + { + return times[count]; + } + return std::numeric_limits::infinity(); + } + + void reset() + { + num_steps = 0; + count = 0; + } + + void initialize(const Real t) + { + while (next_time() < t) + { + ++count; + } + } + + void fire() + { + ++num_steps; + ++count; + } + +public: + + std::vector times; + size_t num_steps; + size_t count; +}; + +struct FixedIntervalEvent +{ + FixedIntervalEvent(const Real& dt = std::numeric_limits::infinity()) + : t0(0.0), dt(dt), num_steps(0), count(0) + { + ; + } + + virtual ~FixedIntervalEvent() + { + ; + } + + void set_dt(const Real& value) + { + dt = value; + } + + const Real next_time() const + { + return t0 + dt * count; + } + + void reset() + { + num_steps = 0; + count = 0; + t0 = 0; //DUMMY + } + + void initialize(const Real t) + { + if (dt <= 0.0) + { + throw std::invalid_argument( + ""A step interval must be positive.""); + } + + if (count == 0) + { + t0 = t; + } + else + { + while (next_time() < t) + { + ++count; + } + } + } + + void fire() + { + ++num_steps; + ++count; + } + +public: + + Real t0, dt; + size_t num_steps; + size_t count; +}; + +template +class TrajectoryObserver + : public Observer +{ +public: + + typedef Observer base_type; + typedef Tevent_ event_type; + +public: + + TrajectoryObserver( + const std::vector& pids, + const bool resolve_boundary = default_resolve_boundary(), + const Real subdt = default_subdt()) + : base_type(false), event_(), subevent_(subdt > 0 ? subdt : std::numeric_limits::infinity()), + pids_(pids), resolve_boundary_(resolve_boundary), prev_positions_(pids.size()), + trajectories_(pids.size()), strides_(pids.size()), t_() + { + ; + } + + TrajectoryObserver( + const bool resolve_boundary = default_resolve_boundary(), + const Real subdt = default_subdt()) + : base_type(false), event_(), subevent_(subdt > 0 ? subdt : std::numeric_limits::infinity()), + pids_(), resolve_boundary_(resolve_boundary), prev_positions_(), + trajectories_(), strides_(), t_() + { + ; + } + + TrajectoryObserver( + const std::vector& pids, + const bool resolve_boundary, + const Real subdt, + const std::vector& prev_positions, + const std::vector >& trajectories, + const std::vector& strides, + const std::vector& t + ) + : base_type(false), event_(), subevent_(subdt > 0 ? subdt : std::numeric_limits::infinity()), + pids_(pids), resolve_boundary_(resolve_boundary), prev_positions_(prev_positions), + trajectories_(trajectories), strides_(strides), t_(t) + { + assert(pids_.size() == prev_positions_.size()); + assert(pids_.size() == trajectories_.size()); + assert(pids_.size() == strides_.size()); + } + + virtual ~TrajectoryObserver() + { + ; + } + + static inline bool default_resolve_boundary() + { + return true; + } + + static inline const Real default_subdt() + { + return 0; + } + + const Real next_time() const + { + return std::min(event_.next_time(), subevent_.next_time()); + } + + const Integer num_steps() const + { + return event_.num_steps + subevent_.num_steps; + } + + const Integer count() const + { + return event_.count; + } + + void initialize(const std::shared_ptr& world, const std::shared_ptr& model) + { + event_.initialize(world->t()); + subevent_.initialize(world->t()); + + typedef std::vector > particle_id_pairs; + if (pids_.size() == 0) + { + particle_id_pairs const particles(world->list_particles()); + pids_.reserve(particles.size()); + for (particle_id_pairs::const_iterator i(particles.begin()); + i != particles.end(); ++i) + { + if ((*i).second.D() > 0) + { + pids_.push_back((*i).first); + } + } + } + + prev_positions_.resize(pids_.size()); + trajectories_.resize(pids_.size()); + strides_.resize(pids_.size()); + } + + bool fire(const Simulator* sim, const std::shared_ptr& world) + { + if (subevent_.next_time() <= event_.next_time()) + { + fire_subevent(sim, world); + } + else + { + fire_event(sim, world); + } + return true; + } + + void reset() + { + prev_positions_.clear(); + prev_positions_.resize(pids_.size(), Real3(0, 0, 0)); + trajectories_.clear(); + trajectories_.resize(pids_.size(), std::vector()); + strides_.clear(); + strides_.resize(pids_.size(), Real3(0, 0, 0)); + t_.clear(); + } + + const event_type& event() const + { + return event_; + } + + void set_event(const event_type& event) + { + event_ = event; + } + + const FixedIntervalEvent& subevent() const + { + return subevent_; + } + + void set_subevent(const FixedIntervalEvent& subevent) + { + subevent_ = subevent; + } + + const std::vector& pids() const + { + return pids_; + } + + const bool resolve_boundary() const + { + return resolve_boundary_; + } + + const std::vector& prev_positions() const + { + return prev_positions_; + } + + const std::vector >& data() const + { + return trajectories_; + } + + const std::vector& strides() const + { + return strides_; + } + + const std::vector& t() const + { + return t_; + } + + const Integer num_tracers() const + { + return pids_.size(); + } + +protected: + + void fire_event(const Simulator* sim, const std::shared_ptr& world) + { + t_.push_back(world->t()); + + const Real3 edge_lengths(world->edge_lengths()); + std::vector::const_iterator j(prev_positions_.begin()); + std::vector::const_iterator k(strides_.begin()); + std::vector >::iterator l(trajectories_.begin()); + for (std::vector::const_iterator i(pids_.begin()); + i != pids_.end(); ++i) + { + if (world->has_particle(*i)) + { + const Real3& stride(*k); + Real3 pos(stride + world->get_particle(*i).second.position()); + + if (resolve_boundary_ && subevent_.num_steps > 0) + { + const Real3& prev(*j); + + for (unsigned int dim(0); dim != 3; ++dim) + { + const Real L(edge_lengths[dim]); + if (pos[dim] - prev[dim] >= L * 0.5) + { + pos[dim] -= L; + } + else if (pos[dim] - prev[dim] <= L * -0.5) + { + pos[dim] += L; + } + } + } + + (*l).push_back(pos); + } + ++j; + ++k; + ++l; + } + + event_.fire(); + } + + void fire_subevent(const Simulator* sim, const std::shared_ptr& world) + { + if (resolve_boundary_) + { + const Real3 edge_lengths(world->edge_lengths()); + std::vector::iterator j(prev_positions_.begin()); + std::vector::iterator k(strides_.begin()); + for (std::vector::const_iterator i(pids_.begin()); + i != pids_.end(); ++i) + { + if (world->has_particle(*i)) + { + Real3& stride(*k); + Real3 pos(stride + world->get_particle(*i).second.position()); + if (subevent_.num_steps > 0) + { + const Real3& prev(*j); + for (unsigned int dim(0); dim != 3; ++dim) + { + const Real L(edge_lengths[dim]); + if (pos[dim] - prev[dim] >= L * 0.5) + { + stride[dim] -= L; + pos[dim] -= L; + } + else if (pos[dim] - prev[dim] <= L * -0.5) + { + stride[dim] += L; + pos[dim] += L; + } + } + } + (*j) = pos; + } + ++j; + ++k; + } + } + + subevent_.fire(); + } + +protected: + + event_type event_; + FixedIntervalEvent subevent_; + + std::vector pids_; + bool resolve_boundary_; + std::vector prev_positions_; + std::vector > trajectories_; + std::vector strides_; + std::vector t_; +}; + +class FixedIntervalTrajectoryObserver + : public TrajectoryObserver +{ +public: + + typedef FixedIntervalEvent event_type; + typedef TrajectoryObserver base_type; + +public: + + FixedIntervalTrajectoryObserver( + const Real& dt, const std::vector& pids, + const bool resolve_boundary = default_resolve_boundary(), + const Real subdt = default_subdt()) + : base_type(pids, resolve_boundary, (subdt > 0 ? subdt : dt)) + { + event_.set_dt(dt); + } + + FixedIntervalTrajectoryObserver( + const Real& dt, + const bool resolve_boundary = default_resolve_boundary(), + const Real subdt = default_subdt()) + : base_type(resolve_boundary, (subdt > 0 ? subdt : dt)) + { + event_.set_dt(dt); + } + + FixedIntervalTrajectoryObserver( + const Real& dt, + const std::vector& pids, + const bool resolve_boundary, + const Real subdt, + const std::vector& prev_positions, + const std::vector >& trajectories, + const std::vector& strides, + const std::vector& times + ) + : base_type(pids, resolve_boundary, subdt, prev_positions, trajectories, strides, times) + { + event_.set_dt(dt); + } + + virtual ~FixedIntervalTrajectoryObserver() + { + ; + } +}; + +class TimingTrajectoryObserver + : public TrajectoryObserver +{ +public: + + typedef TimingEvent event_type; + typedef TrajectoryObserver base_type; + +public: + + TimingTrajectoryObserver( + const std::vector& t, const std::vector& pids, + const Real subdt = default_subdt()) + : base_type(pids, (subdt > 0), subdt) + { + event_.set_times(t); + } + + TimingTrajectoryObserver( + const std::vector& t, + const Real subdt = default_subdt()) + : base_type((subdt > 0), subdt) + { + event_.set_times(t); + } + + TimingTrajectoryObserver( + const std::vector& t, + const std::vector& pids, + const Real subdt, + const std::vector& prev_positions, + const std::vector >& trajectories, + const std::vector& strides, + const std::vector& times + ) + : base_type(pids, (subdt > 0), subdt, prev_positions, trajectories, strides, times) + { + event_.set_times(t); + } + + virtual ~TimingTrajectoryObserver() + { + ; + } +}; + +class TimeoutObserver + : public Observer +{ +public: + + typedef Observer base_type; + +public: + + TimeoutObserver() + : base_type(true), interval_(std::numeric_limits::infinity()), duration_(0.0), acc_(0.0) + { + ; + } + + TimeoutObserver(const Real interval, const Real duration=0.0, const Real acc=0.0) + : base_type(true), interval_(interval), duration_(duration), acc_(acc) + { + ; + } + + virtual ~TimeoutObserver() + { + ; + } + + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual void finalize(const std::shared_ptr& world); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + + const Real interval() const + { + return interval_; + } + + const Real duration() const + { + return duration_; + } + + const Real accumulation() const + { + return acc_; + } + + const std::chrono::system_clock::time_point& start_time_point() const + { + return tstart_; + } + + void set_start_time_point(const std::chrono::system_clock::time_point& tstart) + { + tstart_ = tstart; + } + +protected: + + Real interval_; + Real duration_; + Real acc_; + std::chrono::system_clock::time_point tstart_; +}; + +class FixedIntervalTrackingObserver + : public Observer +{ +public: + + typedef Observer base_type; + +public: + + FixedIntervalTrackingObserver( + const Real& dt, const std::vector& species, + const bool& resolve_boundary = default_resolve_boundary(), const Real subdt = default_subdt(), + const Real threshold = default_threshold()) + : base_type(false), event_(dt), subevent_(subdt > 0 ? subdt : dt), + species_(species), resolve_boundary_(resolve_boundary), + threshold_(threshold > 0 ? threshold : std::numeric_limits::infinity()), + prev_positions_(), strides_(), pids_(), trajectories_(), t_() + { + ; + } + + FixedIntervalTrackingObserver( + const Real& dt, + const std::vector& pids, + const bool& resolve_boundary, + const Real subdt, + const std::vector& prev_positions, + const std::vector >& trajectories, + const std::vector& strides, + const std::vector& times, + const std::vector& species, + const Real threshold + ) + : base_type(false), event_(dt), subevent_(subdt > 0 ? subdt : dt), + pids_(pids), resolve_boundary_(resolve_boundary), + prev_positions_(prev_positions), trajectories_(trajectories), strides_(strides), t_(times), + species_(species), + threshold_(threshold > 0 ? threshold : std::numeric_limits::infinity()) + { + ; + } + + virtual ~FixedIntervalTrackingObserver() + { + ; + } + + static inline bool default_resolve_boundary() + { + return true; + } + + static inline const Real default_subdt() + { + return 0; + } + + static inline const Real default_threshold() + { + return 0; + } + + const Real next_time() const; + const Integer num_steps() const; + const Integer count() const; + const Integer num_tracers() const; + virtual void initialize(const std::shared_ptr& world, const std::shared_ptr& model); + virtual bool fire(const Simulator* sim, const std::shared_ptr& world); + virtual void reset(); + + const std::vector >& data() const; + const std::vector& t() const; + + Real distance_sq( + const Real3& pos1, const Real3& pos2, const Real3& edge_lengths) const + { + Real retval(0); + for (Real3::size_type dim(0); dim < 3; ++dim) + { + const Real edge_length(edge_lengths[dim]); + const Real diff(pos2[dim] - pos1[dim]), half(edge_length * 0.5); + + if (diff > half) + { + retval += pow_2(diff - edge_length); + } + else if (diff < -half) + { + retval += pow_2(diff + edge_length); + } + else + { + retval += pow_2(diff); + } + } + return retval; + } + + inline Real distance(const Real3& pos1, const Real3& pos2, const Real3& edge_lengths) const + { + return std::sqrt(distance_sq(pos1, pos2, edge_lengths)); + } + + const FixedIntervalEvent& event() const + { + return event_; + } + + void set_event(const FixedIntervalEvent& event) + { + event_ = event; + } + + const FixedIntervalEvent& subevent() const + { + return subevent_; + } + + void set_subevent(const FixedIntervalEvent& subevent) + { + subevent_ = subevent; + } + + const std::vector& pids() const + { + return pids_; + } + + const bool resolve_boundary() const + { + return resolve_boundary_; + } + + const std::vector& prev_positions() const + { + return prev_positions_; + } + + const std::vector& strides() const + { + return strides_; + } + + const std::vector& species() const + { + return species_; + } + + const Real threshold() const + { + return threshold_; + } + +protected: + + void fire_event(const Simulator* sim, const std::shared_ptr& world); + void fire_subevent(const Simulator* sim, const std::shared_ptr& world); + +protected: + + FixedIntervalEvent event_, subevent_; + + std::vector species_; + bool resolve_boundary_; + Real threshold_; + + std::vector prev_positions_; + std::vector strides_; + std::vector pids_; + std::vector > trajectories_; + std::vector t_; +}; + +} // ecell4 + +#endif /* ECELL4_OBSERVER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/PolygonHDF5Writer.hpp",".hpp","419","23","#ifndef ECELL4_POLYGON_HDF5_WRITER_HPP +#define ECELL4_POLYGON_HDF5_WRITER_HPP + +#include +#include + +#include +#include + +#include ""types.hpp"" +#include ""Triangle.hpp"" + +namespace ecell4 +{ + +class Polygon; // forward declaration + +void save_polygon_hdf5(const Polygon&, H5::Group*); +void load_polygon_hdf5(const H5::Group&, Polygon*); + +} // ecell4 +#endif// ECELL4_POLYGON_HDF5_WRITER_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/types.hpp",".hpp","261","18","#ifndef ECELL4_TYPES_HPP +#define ECELL4_TYPES_HPP + +#include +#define _USE_MATH_DEFINES +#include +#include +#include + +namespace ecell4 +{ + +typedef int64_t Integer; +typedef double Real; + +} // ecell4 +#endif /* ECELL4_TYPES_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/BoundaryCondition.hpp",".hpp","3487","120","#ifndef ECELL4_BOUNDARY_CONDITION_HPP +#define ECELL4_BOUNDARY_CONDITION_HPP +#include ""types.hpp"" +#include ""exceptions.hpp"" +#include ""Real3.hpp"" +#include + +namespace ecell4 +{ + +class Boundary +{ +public: + virtual ~Boundary() = default; + virtual Real3 periodic_transpose(const Real3&, const Real3&) const noexcept = 0; + virtual Real3 apply_boundary (const Real3&) const noexcept = 0; + virtual Real3 const& edge_lengths() const noexcept = 0; + virtual void reset(const Real3&) noexcept = 0; +}; + +class UnlimitedBoundary final : public Boundary +{ +public: + + UnlimitedBoundary() noexcept : + edge_lengths_(std::numeric_limits::infinity(), + std::numeric_limits::infinity(), + std::numeric_limits::infinity()) + {} + explicit UnlimitedBoundary(const Real3& /*ignored*/) noexcept : + edge_lengths_(std::numeric_limits::infinity(), + std::numeric_limits::infinity(), + std::numeric_limits::infinity()) + {} + ~UnlimitedBoundary() override = default; + UnlimitedBoundary(const UnlimitedBoundary&) = default; + UnlimitedBoundary(UnlimitedBoundary&&) = default; + UnlimitedBoundary& operator=(const UnlimitedBoundary&) = default; + UnlimitedBoundary& operator=(UnlimitedBoundary&&) = default; + + Real3 periodic_transpose(const Real3& pos, const Real3&) const noexcept override + { + return pos; + } + Real3 apply_boundary(const Real3& pos) const noexcept override + { + return pos; + } + Real3 const& edge_lengths() const noexcept override + { + return this->edge_lengths_; + } + void reset(const Real3&) noexcept override + { + return ; + } + +private: + Real3 edge_lengths_; +}; + +class PeriodicBoundary final : public Boundary +{ +public: + + PeriodicBoundary() noexcept + : edge_lengths_(0.0, 0.0, 0.0), half_widths_(0.0, 0.0, 0.0) + {} + explicit PeriodicBoundary(const Real3& edges) noexcept + : edge_lengths_(edges), half_widths_(edges * 0.5) + {} + ~PeriodicBoundary() override = default; + PeriodicBoundary(const PeriodicBoundary&) = default; + PeriodicBoundary(PeriodicBoundary&&) = default; + PeriodicBoundary& operator=(const PeriodicBoundary&) = default; + PeriodicBoundary& operator=(PeriodicBoundary&&) = default; + + // transpose pos1 relative to pos2 + Real3 periodic_transpose(const Real3& pos1, const Real3& pos2) const noexcept override + { + Real3 retval(pos1); + for(Real3::size_type dim(0); dim < 3; ++dim) + { + const Real edge_length(edge_lengths_[dim]); + const Real diff(pos2[dim] - pos1[dim]), half(half_widths_[dim]); + + if (diff > half) + { + retval[dim] += edge_length; + } + else if (diff < -half) + { + retval[dim] -= edge_length; + } + } + return retval; + } + Real3 apply_boundary(const Real3& pos) const noexcept override + { + return modulo(pos, this->edge_lengths_); + } + Real3 const& edge_lengths() const noexcept override + { + return edge_lengths_; + } + void reset(const Real3& edges) noexcept override + { + this->edge_lengths_ = edges; + this->half_widths_ = edges * 0.5; + return ; + } + +private: + Real3 edge_lengths_; + Real3 half_widths_; +}; + +} // ecell4 +#endif//ECELL4_BOUNDARY_CONDITION_HPP +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Polygon.cpp",".cpp","47755","1177","#include +#include +#include +#include +#include + +namespace ecell4 +{ + +const Real Polygon::absolute_tolerance = 1e-12; +const Real Polygon::relative_tolerance = 1e-8; + +void Polygon::assign(const std::vector& ts) +{ + constexpr Real pi = boost::math::constants::pi(); + const Real tol_abs2 = absolute_tolerance * absolute_tolerance; + const Real tol_rel2 = relative_tolerance * relative_tolerance; + + // To make IDs after saving/loading the triangles, IDGenerators should be + // re-initialized here. + + vertex_idgen_ = SerialIDGenerator{}; + face_idgen_ = SerialIDGenerator{}; + edge_idgen_ = SerialIDGenerator{}; + + vertices_.clear(); + faces_.clear(); + edges_.clear(); + this->total_area_ = 0.0; + + // prepair temporal data storage + typedef std::pair fid_vidx_pair; + typedef std::pair> tmp_vtx_type; + typedef boost::container::flat_map tmp_vertex_map; + tmp_vertex_map tmp_vtxs; + + // first, generate (FaceIDs for all triangles) and (EdgeIDs for all Edges). + // and collect vertices that are at the same position. + for(const Triangle& triangle : ts) + { + this->total_area_ += triangle.area(); + + const FaceID fid = face_idgen_(); + face_data fd; + fd.triangle = triangle; + + for(std::size_t i=0; i<3; ++i) + { + const Real3& v1 = triangle.vertices()[i]; + boost::optional found_vtx = boost::none; + + // find near vertex + for(auto& vid_vtx : tmp_vtxs) + { + const Real3& v2 = vid_vtx.second.first; + const Real dist2 = + length_sq(this->periodic_transpose(v1, v2) - v2); + + if(dist2 < tol_abs2 || dist2 < tol_rel2 * length_sq(v1)) + { + // vertex that locates near the vertex found + found_vtx = vid_vtx.first; + auto& vtx = vid_vtx.second; + + // calculating mean position on the fly. + vtx.first = (v2 * vtx.second.size() + this->periodic_transpose(v1, v2)) / + (vtx.second.size() + 1); + // assign face-id to the vertex + vtx.second.push_back(std::make_pair(fid, i)); + break; + } + } + if(!found_vtx) // new vertices! add VertexID. + { + const VertexID new_vid = this->vertex_idgen_(); + tmp_vtxs[new_vid] = std::make_pair(this->apply_boundary(v1), + std::vector(1, std::make_pair(fid, i))); + found_vtx = new_vid; + } + fd.vertices[i] = *found_vtx; // store vertex id to face data + } + + // make 3 edges around the face + for(std::size_t i=0; i<3; ++i) + { + // in this point, edge length and direction are not fixed (because + // vertex positions are corrected after all the faces are assigned). + const EdgeID eid = this->edge_idgen_(); + edge_data ed; + ed.face = fid; + ed.target = fd.vertices[i==2?0:i+1]; + this->edges_.update(eid, ed); + + fd.edges[i] = eid; + } + // set `next` of these 3 edges + for(std::size_t i=0; i<3; ++i) + { + this->edge_at(fd.edges[i]).next = fd.edges[i==2?0:i+1]; + } + faces_.update(fid, fd); + } + + // * assign tmp_vtxs to this->vertices_ + // * set outgoing_edges without order + for(const auto& vid_vtx : tmp_vtxs) + { + const VertexID vid = vid_vtx.first; + const Real3 pos = vid_vtx.second.first; + const std::vector& face_pos = vid_vtx.second.second; + + vertex_data vd; + vd.position = pos; + + // * set vertex.outgoing_edges, but not sorted. + for(const auto& fid_vidx : face_pos) + { + const FaceID fid = fid_vidx.first; + const std::size_t idx = fid_vidx.second; + face_data& fd = this->face_at(fid); + + assert(vid == fd.vertices[idx]); + vd.outgoing_edges.push_back(std::make_pair(fd.edges[idx], 0.0)); + } + this->vertices_.update(vid, vd); + } + + // refine vertex positions + // - keep the absolute position to allow out-of-bound vertices + // - make vertex positions semantically the same + // - if a vertex shares triangles, put vertices on the triangles together + for(auto& fidf : this->faces_) + { + face_data& fd = fidf.second; + std::array vs = fd.triangle.vertices(); + vs[0] = this->periodic_transpose( + this->vertex_at(fd.vertices[0]).position, vs[0]); + vs[1] = this->periodic_transpose( + this->vertex_at(fd.vertices[1]).position, vs[1]); + vs[2] = this->periodic_transpose( + this->vertex_at(fd.vertices[2]).position, vs[2]); + fd.triangle = Triangle(vs); + } + + // set edge.length, edge.direction by using face.traingle + for(const auto& fidf : this->faces_) + { + for(std::size_t i=0; i<3; ++i) + { + const EdgeID eid = fidf.second.edges[i]; + this->edge_at(eid).length = fidf.second.triangle.length_of_edge_at(i); + this->edge_at(eid).direction = fidf.second.triangle.edge_at(i); + } + } + + // search pairs of opposite edges & calculate edge.tilt. + for(const auto& eide : this->edges_) + { + const EdgeID eid = eide.first; + const VertexID start = this->target_of(eid); + const VertexID target = this->target_of( + this->next_of(this->next_of(eid))); + + bool opposite_found = false; + for(const auto& eid_angle : this->vertex_at(start).outgoing_edges) + { + const EdgeID outgoing = eid_angle.first; + if(this->target_of(outgoing) == target) + { + // found opposite edge! calculate tilt... + this->edge_at(eid).opposite_edge = outgoing; + + const FaceID fid1 = face_of(eid); + const FaceID fid2 = face_of(outgoing); + const Real3 n1 = this->face_at(fid1).triangle.normal(); + const Real3 n2 = this->face_at(fid2).triangle.normal(); + const Real3 cr = cross_product(this->edge_at(eid).direction, n1); + const Real sg = dot_product(cr, n2); + const Real ang = calc_angle(n1, n2) * (sg > 0 ? 1 : -1); + + this->edge_at(eid ).tilt = ang; + this->edge_at(outgoing).tilt = ang; + + opposite_found = true; + break; + } + } + if(!opposite_found) + { + throw ecell4::NotSupported(""The given polygon is not closed.""); + } + } + + // set vertex_data.angle by traversing edges. + for(auto& vidv : this->vertices_) + { + auto& vtx = vidv.second; + const std::size_t num_edges = vtx.outgoing_edges.size(); + std::vector outgoing_edges_tmp(vtx.outgoing_edges.size()); + for(std::size_t idx=0; idxface_at(this->face_of(current)); + Real angle = std::numeric_limits::max(); + for(std::size_t idx=0; idx<3; ++idx) + { + if(f.edges[idx] == current) + { + angle = f.triangle.angle_at(idx); + break; + } + } + assert(angle != std::numeric_limits::max()); + + total_angle += angle; + vtx.outgoing_edges.push_back(std::make_pair(current, angle)); + current = this->opposite_of(this->next_of(this->next_of(current))); + } + while(current != start); + + vtx.apex_angle = total_angle; + + if(!outgoing_edges_tmp.empty()) + { + std::cout << outgoing_edges_tmp.size() << std::endl; + for(const auto& oet: outgoing_edges_tmp) + { + const auto fid = this->face_of(oet); + std::cout << oet << "": on "" << fid << "", {""; + const face_data& f = this->face_at(fid); + for(std::size_t idx=0; idx<3; ++idx) + { + std::cout << f.triangle.vertex_at(idx); + if(idx != 2) {std::cout << "", "";} + } + std::cout << ""}, ""; + for(std::size_t idx=0; idx<3; ++idx) + { + if(f.edges[idx] == oet) + { + std::cout << f.triangle.vertex_at(idx) << "" -> ""; + std::cout << f.triangle.vertex_at(idx==2?0:idx+1); + std::cout << std::endl; + break; + } + } + } + } + if(!outgoing_edges_tmp.empty()) + { + throw std::runtime_error(""Polygon::assign: internal error: "" + ""cannot traverse all the outgoing edges from a vertex""); + } + if(vtx.outgoing_edges.size() != num_edges) + { + throw std::runtime_error(""Polygon::assign: internal error: "" + ""inconsistent number of outgoing edges""); + } + } + + // make neighbor list for faces! + for(auto& fidf : this->faces_) + { + auto& face = fidf.second; + for(std::size_t i=0; i<3; ++i) + { + const VertexID vid = face.vertices[i]; + const Real3 v_pos = face.triangle.vertex_at(i); + const Real3 normal = face.triangle.normal(); + + // counter clock wise + { + const Real3 ref_edge = face.triangle.edge_at(i==0?2:i-1) / + (-length(face.triangle.edge_at(i==0?2:i-1))); + + face.neighbor_ccw[i].clear(); + const auto start_edge = face.edges[i]; + EdgeID current_edge = opposite_of(next_of(next_of(start_edge))); + Real current_angle = 0.0; + while(current_edge != start_edge) + { + const FaceID fid = face_of(current_edge); + + const std::size_t vidx0 = this->face_at(fid).index_of(vid); + const std::size_t vidx1 = this->face_at(fid).index_of( + target_of(current_edge)); + const std::size_t vidx2 = this->face_at(fid).index_of( + target_of(next_of(current_edge))); + assert(vidx0 < 3); + assert(vidx1 < 3); + assert(vidx2 < 3); + + const Real next_angle = current_angle + + this->face_at(fid).triangle.angle_at(vidx0); + + std::array unfolded; + unfolded[vidx0] = v_pos; + unfolded[vidx1] = v_pos + + rotate(current_angle, normal, ref_edge) * + length_of(current_edge); + unfolded[vidx2] = v_pos + + rotate(next_angle, normal, ref_edge) * + length_of(next_of(next_of(current_edge))); + + face.neighbors.push_back(fid); + face.neighbor_ccw[i].emplace_back(fid, Triangle(unfolded)); + + current_angle = next_angle; + current_edge = opposite_of(next_of(next_of(current_edge))); + } + } + + // clock wise + { + const Real3 ref_edge = face.triangle.edge_at(i) / + length(face.triangle.edge_at(i)); + + face.neighbor_cw[i].clear(); + const auto start_edge = face.edges[i]; + EdgeID current_edge = next_of(opposite_of(start_edge)); + Real current_angle = 0.0; + while(current_edge != start_edge) + { + const FaceID fid = face_of(current_edge); + + const std::size_t vidx0 = this->face_at(fid).index_of(vid); + const std::size_t vidx1 = this->face_at(fid).index_of( + target_of(current_edge)); + const std::size_t vidx2 = this->face_at(fid).index_of( + target_of(next_of(current_edge))); + assert(vidx0 < 3); + assert(vidx1 < 3); + assert(vidx2 < 3); + + const Real next_angle = current_angle + + this->face_at(fid).triangle.angle_at(vidx0); + + std::array unfolded; + unfolded[vidx0] = v_pos; + unfolded[vidx1] = v_pos + + rotate(-next_angle, normal, ref_edge) * + length_of(current_edge); + unfolded[vidx2] = v_pos + + rotate(-current_angle, normal, ref_edge) * + length_of(next_of(next_of(current_edge))); + + face.neighbors.push_back(fid); + face.neighbor_cw[i].emplace_back(fid, Triangle(unfolded)); + + current_angle = next_angle; + current_edge = next_of(opposite_of(current_edge)); + } + } + } + std::sort(face.neighbors.begin(), face.neighbors.end()); + const auto last = std::unique(face.neighbors.begin(), face.neighbors.end()); + face.neighbors.erase(last, face.neighbors.end()); + } + return; +} + +Real Polygon::distance_sq(const std::pair& pos1, + const std::pair& pos2) const +{ + typedef utils::pair_first_element_unary_predicator + face_finder_type; + constexpr Real pi = boost::math::constants::pi(); + + // if two particles are on the same face, return just a 3D distance. + if(pos1.second == pos2.second) + { + return length_sq(pos2.first - pos1.first); + } + + // If positions are on different faces, there can be several cases. + // 1.) ______ + // /\ /\ | The positions are on the faces connected by a vertex. + // / \ /p2\ | using p1-vtx-p2 angle and the low-of-cosines, the + // /____\/____\ | minimum distance on the surface can be calculated. + // /\ / | + // /p1\ / | + // /____\/ | + // + // 2.) ______ + // /\ p2 / | The positions are on the faces that are not connected + // / \ / | by any vertex. There can be several options to unfold + // /____\/ | the polygon to make the particles on the same plane. + // /\ / | In this case, finding the minimum path is too difficult + // /p1\ / | to use in simulation, so just returns inf. In the SGFRD + // /____\/ | simulation, movement from p1 to p2 is inhibited. + // + // 3.) ______ + // /\ /\ | The positions are on the faces connected by a vertex + // /p2\ / \ | and the apex angle exceeds 360 degree. There can be 2 + // /____\/____\ | pathes, counter-clockwise and clockwise, and both angle + // /\ / | exceeds 180 degree. In this case, the minimum distance + // /p1\ / | pathway goes across the vertex. + // /____\/ | + // + // 4.) ......... ______ + // /\connected\ /\ | The particles are on the faces connected by a + // / \ <=====> \ / \ | vertex and the apex angle exceeds 360 degree. + // /____\.........\/____\ | And the triangles overlaps when unfolded. + // \ /\ /\ / | In this case, we must use the minimum angle + // \ /p2\ /p1\ / | because just unfolding triangle makes minimum + // \/____\ /____\/ | pathway shorter than the 3D distance. + // + // 5.) + // \`.p1 | If a polygon is severely deformed, the minimum + // \o`. | angle pathway can protrude the face. To avoid this, + // ^ `. | It is required to check the minimum angle pathway + // |\___`.vertex | goes across all the edges. + // |/ .' | + // v .' | + // /o.' | + // /.'p2 | + // + + const Real3& p1 = pos1.first; + const Real3& p2 = pos2.first; + const FaceID f1 = pos1.second; + const FaceID f2 = pos2.second; + + // for comparison + const auto min_edge_length = std::min(edge_length_[0], + std::min(edge_length_[1], edge_length_[2])); + const auto rel_tol = relative_tolerance * min_edge_length; + + const face_data& face = face_at(f1); + const Real3& normal = face.triangle.normal(); + + boost::container::static_vector connecting_vtxs; + + Real distance_sq = std::numeric_limits::infinity(); + for(std::size_t i=0; i<3; ++i) + { + // counter clockwise + // + // ^ vertices[i] + // edge[i] /|\ + // / |~\ + // / o \ next(next(egde[i])) + // v______>\ + // next(edge[i]) + + const VertexID vid = face.vertices[i]; + const Real3& vpos = position_at(vid); + const Real3 vtop1 = this->periodic_transpose(p1, vpos) - vpos; + const Real3 vtop2 = this->periodic_transpose(p2, vpos) - vpos; + const Real3 p1tov = vtop1 * (-1.0); + + // check p1 or p2 are exactly on the vertex. + // If they are on, it causes NaN because the length of v->p vector is 0. + const Real vtop1_len = length(p1tov); + const Real vtop2_len = length(vtop2); + if(vtop1_len < relative_tolerance * min_edge_length) + { + // pos1 locates exactly on the vtx. distance from pos1 to pos2 is + // equal to the distance from vtx to pos2. + + // if the face on which pos2 locates has the vertex, the squared + // distance is just vtop2_len^2. + + const auto& vtxs = this->vertices_of(f2); + if(std::find(vtxs.begin(), vtxs.end(), vid) != vtxs.end()) + { + distance_sq = std::min(distance_sq, vtop2_len * vtop2_len); + } + continue; + } + if(vtop2_len < relative_tolerance * min_edge_length) + { + // pos2 locates exactly on the vtx. distance from pos1 to pos2 is + // equal to the distance from pos1 to vtx. + + const auto& vtxs = this->vertices_of(f2); + if(std::find(vtxs.begin(), vtxs.end(), vid) != vtxs.end()) + { + distance_sq = std::min(distance_sq, vtop1_len * vtop1_len); + } + continue; + } + + // calc the initial angle + const auto init_angle = calc_angle(p1tov, face.triangle.edge_at(i==0?2:i-1)); + Real angle = init_angle; + const Real apex_angle = apex_angle_at(vid); + + // ------------------------------------------------------------------ + // search `f2` + bool connected = false; + for(const auto& neighbor : face.neighbor_ccw[i]) + { + assert(neighbor.first != f1); + + const auto& nface = face_at(neighbor.first); + const auto vidx = nface.index_of(vid); + if(neighbor.first == f2) + { + angle += calc_angle(vtop2, nface.triangle.edge_at(vidx)); + connected = true; + break; + } + angle += nface.triangle.angle_at(vidx); + } + if(!connected) + { + continue; + } + connecting_vtxs.push_back(vpos); + + // ------------------------------------------------------------------ + // calculate the minimum angle + + const Real angle_ccw = angle; + const Real angle_cw = apex_angle - angle; + assert(angle_cw >= 0.0); + const Real min_angle = std::min(angle_ccw, angle_cw); + + // skip case 3 (theta > 180 deg). + if(min_angle > pi) {continue;} + + // if the minimum angle < 180 degree, its case 1. + // calculate distance using the low of cosine. + + // Before calculating the distance, check whether this is the case 5. + // If a vertex locates inside of a triangle formed by a vertex, p1, and + // p2, then it is case 5 and the pathway is not available. + + bool is_case5 = false; + if(angle_ccw < angle_cw) // the min dist pathway is counter-clockwise + { + const auto sin_ccw = std::sin(angle_ccw); + const auto cos_ccw = std::cos(angle_ccw); + + angle = init_angle; + for(const auto& neighbor : face.neighbor_ccw[i]) + { + if(neighbor.first == f2) {break;} + + const auto& nface = face_at(neighbor.first); + const auto vidx = nface.index_of(vid); + + const auto sin_agl = std::sin(angle); + const auto cos_agl = std::cos(angle); + + // sin of the opposite angle (angle_ccw - angle) + const auto sin_opp = sin_ccw * cos_agl - cos_ccw * sin_agl; + + const auto threshold = vtop1_len * vtop2_len * sin_ccw / + (vtop1_len * sin_agl + vtop2_len * sin_opp); + + if(nface.triangle.length_of_edge_at(vidx) < threshold * (1.0 - relative_tolerance)) + { + is_case5 = true; + break; + } + angle += nface.triangle.angle_at(vidx); + } + } + else // the minimum distance pathway is clockwise + { + const auto sin_cw = std::sin(angle_cw); + const auto cos_cw = std::cos(angle_cw); + + angle = face.triangle.angle_at(i) - init_angle; + for(const auto& neighbor : face.neighbor_cw[i]) + { + if(neighbor.first == f2) {break;} + + const auto& nface = face_at(neighbor.first); + const auto vidx = nface.index_of(vid); + + const auto sin_agl = std::sin(angle); + const auto cos_agl = std::cos(angle); + + // sin of the opposite angle (angle_cw - angle) + const auto sin_opp = sin_cw * cos_agl - cos_cw * sin_agl; + + const auto threshold = vtop1_len * vtop2_len * sin_cw / + (vtop1_len * sin_agl + vtop2_len * sin_opp); + + const auto edge_idx = (vidx==0) ? 2 : vidx-1; + if(nface.triangle.length_of_edge_at(edge_idx) < threshold * (1.0 - relative_tolerance)) + { + is_case5 = true; + break; + } + angle += nface.triangle.angle_at(vidx); + } + } + if(is_case5) // no available path. + { + continue; + } + + Real rotation_angle = min_angle; + if(angle_cw < angle_ccw) + { + rotation_angle *= -1; // rotate it clockwise + } + const auto vtop2_unf = rotate(rotation_angle, normal, vtop1) * + (vtop2_len / vtop1_len); + + distance_sq = std::min(distance_sq, length_sq(vtop1 - vtop2_unf)); + } + if(distance_sq != std::numeric_limits::infinity()) + { + // distance_sq is updated! It founds the minimum path (case 1). + return distance_sq; + } + if(connecting_vtxs.empty()) + { + // if `f1` and `f2` are not connected via any vertex, the distance + // cannot be calculated (case 2). + return std::numeric_limits::infinity(); + } + + // Here, the positions are connected via some vertices but the minimum + // distance is non-trivial. It is case 3. return distance that passes + // through the vertex that connects `f1` and `f2`. + + // here, distance_sq is still infinity. + for(const Real3 vpos : connecting_vtxs) + { + const Real l1 = length(this->periodic_transpose(p1, vpos) - vpos); + const Real l2 = length(this->periodic_transpose(p2, vpos) - vpos); + distance_sq = std::min(distance_sq, (l1 + l2) * (l1 + l2)); + } + return distance_sq; +} + +Real Polygon::distance_sq(const std::pair& pos1, + const std::pair& pos2) const +{ + for(const auto el : this->vertex_at(pos1.second).outgoing_edges) + { + const EdgeID eid = el.first; + const FaceID fid = this->face_of(eid); // face that connects to the vtx + if(fid == pos2.second) + { + // on the same face. + return length_sq( + this->periodic_transpose(pos1.first, pos2.first) - pos2.first); + } + // ______ pos1 + // ^ / + // / \ / + // /adj\ / + // /_____v + + const FaceID adj = this->face_of(this->opposite_of(this->next_of(eid))); + if(adj == pos2.second) + { + // redirects to distance_sq({Real3, FaceID}, {Real3, FaceID}) + // considering pos1 as a position on a face + return distance_sq(std::make_pair(pos1.first, fid), pos2); + } + } + return std::numeric_limits::infinity(); +} + +Real Polygon::distance_sq(const std::pair& pos1, + const std::pair& pos2) const +{ + if(pos1.second == pos2.second) + { + return 0.0; + } + for(const auto el : this->vertex_at(pos1.second).outgoing_edges) + { + const EdgeID eid = el.first; + if(this->target_of(eid) == pos2.second) + { + // directly connected. + const Real l = length_of(eid); + return l * l; + } + + const EdgeID inbetween = this->opposite_of(this->next_of(eid)); + if(this->target_of(this->next_of(inbetween)) == pos2.second) + { + const FaceID fid = this->face_of(eid); + const FaceID adj = this->face_of(inbetween); + + // redirects to distance_sq(face, face) + return distance_sq(std::make_pair(pos1.first, fid), + std::make_pair(pos2.first, adj)); + } + } + return std::numeric_limits::infinity(); +} + +Real Polygon::distance(const std::pair& pos1, + const std::pair& pos2) const +{ + if(pos1.second == pos2.second) + { + return 0.0; + } + for(const auto el : this->vertex_at(pos1.second).outgoing_edges) + { + const EdgeID eid = el.first; + if(this->target_of(eid) == pos2.second) + { + // directly connected. + return length_of(eid); + } + + const EdgeID inbetween = this->opposite_of(this->next_of(eid)); + if(this->target_of(this->next_of(inbetween)) == pos2.second) + { + const FaceID fid = this->face_of(eid); + const FaceID adj = this->face_of(inbetween); + + // redirects to distance(face, face) + return distance(std::make_pair(pos1.first, fid), + std::make_pair(pos2.first, adj)); + } + } + return std::numeric_limits::infinity(); +} + +// return direction from pos1 to pos2 +Real3 Polygon::direction(const std::pair& pos1, + const std::pair& pos2) const +{ + constexpr Real pi = boost::math::constants::pi(); + typedef utils::pair_first_element_unary_predicator + face_finder_type; + + if(pos1.second == pos2.second) + { + return pos2.first - pos1.first; + } + + const Real3& p1 = pos1.first; + const Real3& p2 = pos2.first; + const FaceID f1 = pos1.second; + const FaceID f2 = pos2.second; + + // for comparison + const auto min_edge_length = std::min(edge_length_[0], + std::min(edge_length_[1], edge_length_[2])); + const auto rel_tol = relative_tolerance * min_edge_length; + + const face_data& face = face_at(f1); + const Real3& normal = face.triangle.normal(); + + boost::container::static_vector connecting_vtxs; + + Real distance_sq = std::numeric_limits::infinity(); + Real3 retval(0,0,0); + for(std::size_t i=0; i<3; ++i) + { + // counter clockwise + // + // ^ vertices[i] + // edge[i] /|\ + // / |~\ + // / o \ next(next(egde[i])) + // v______>\ + // next(edge[i]) + + const VertexID vid = face.vertices[i]; + const Real3& vpos = position_at(vid); + const Real3 vtop1 = this->periodic_transpose(p1, vpos) - vpos; + const Real3 vtop2 = this->periodic_transpose(p2, vpos) - vpos; + const Real3 p1tov = vtop1 * (-1.0); + + // check p1 or p2 are exactly on the vertex. + // If they are on, it causes NaN because the length of v->p vector is 0. + const Real vtop1_len = length(p1tov); + const Real vtop2_len = length(vtop2); + if(vtop1_len < relative_tolerance * min_edge_length) + { + // pos1 locates exactly on the vtx. distance from pos1 to pos2 is + // equal to the distance from vtx to pos2. + const auto& vtxs = this->vertices_of(f2); + if(std::find(vtxs.begin(), vtxs.end(), vid) == vtxs.end()) + { + continue; + } + return vtop2; + } + if(vtop2_len < relative_tolerance * min_edge_length) + { + // pos2 locates exactly on the vtx. distance from pos1 to pos2 is + // equal to the distance from pos1 to vtx. + const auto& vtxs = this->vertices_of(f2); + if(std::find(vtxs.begin(), vtxs.end(), vid) == vtxs.end()) + { + continue; + } + return vtop1; + } + + // calc the initial angle + const auto init_angle = calc_angle(p1tov, face.triangle.edge_at(i==0?2:i-1)); + Real angle = init_angle; + const Real apex_angle = apex_angle_at(vid); + + // ------------------------------------------------------------------ + // search `f2` + bool connected = false; + for(const auto& neighbor : face.neighbor_ccw[i]) + { + assert(neighbor.first != f1); + + const auto& nface = face_at(neighbor.first); + const auto vidx = nface.index_of(vid); + if(neighbor.first == f2) + { + angle += calc_angle(vtop2, nface.triangle.edge_at(vidx)); + connected = true; + break; + } + angle += nface.triangle.angle_at(vidx); + } + if(!connected) + { + continue; + } + connecting_vtxs.push_back(vpos); + + // ------------------------------------------------------------------ + // calculate the minimum angle + + const Real angle_ccw = angle; + const Real angle_cw = apex_angle - angle; + assert(angle_cw >= 0.0); + const Real min_angle = std::min(angle_ccw, angle_cw); + + // skip case 3 (theta > 180 deg). + if(min_angle > pi) {continue;} + + // if the minimum angle < 180 degree, its case 1. + // calculate distance using the low of cosine. + + // Before calculating the distance, check whether this is the case 5. + // If a vertex locates inside of a triangle formed by a vertex, p1, and + // p2, then it is case 5 and the pathway is not available. + + bool is_case5 = false; + if(angle_ccw < angle_cw) // the min dist pathway is counter-clockwise + { + const auto sin_ccw = std::sin(angle_ccw); + const auto cos_ccw = std::cos(angle_ccw); + + angle = init_angle; + for(const auto& neighbor : face.neighbor_ccw[i]) + { + if(neighbor.first == f2) {break;} + + const auto& nface = face_at(neighbor.first); + const auto vidx = nface.index_of(vid); + + const auto sin_agl = std::sin(angle); + const auto cos_agl = std::cos(angle); + + // sin of the opposite angle (angle_ccw - angle) + const auto sin_opp = sin_ccw * cos_agl - cos_ccw * sin_agl; + + const auto threshold = vtop1_len * vtop2_len * sin_ccw / + (vtop1_len * sin_agl + vtop2_len * sin_opp); + + if(nface.triangle.length_of_edge_at(vidx) < threshold) + { + is_case5 = true; + break; + } + angle += nface.triangle.angle_at(vidx); + } + } + else // the minimum distance pathway is clockwise + { + const auto sin_cw = std::sin(angle_cw); + const auto cos_cw = std::cos(angle_cw); + + angle = face.triangle.angle_at(i) - init_angle; + for(const auto& neighbor : face.neighbor_cw[i]) + { + if(neighbor.first == f2) {break;} + + const auto& nface = face_at(neighbor.first); + const auto vidx = nface.index_of(vid); + + const auto sin_agl = std::sin(angle); + const auto cos_agl = std::cos(angle); + + // sin of the opposite angle (angle_cw - angle) + const auto sin_opp = sin_cw * cos_agl - cos_cw * sin_agl; + + const auto threshold = vtop1_len * vtop2_len * sin_cw / + (vtop1_len * sin_agl + vtop2_len * sin_opp); + + const auto edge_idx = (vidx==0) ? 2 : vidx-1; + if(nface.triangle.length_of_edge_at(edge_idx) < threshold) + { + is_case5 = true; + break; + } + angle += nface.triangle.angle_at(vidx); + } + } + if(is_case5) // no available path. + { + continue; + } + + Real rotation_angle = min_angle; + if(angle_cw < angle_ccw) + { + rotation_angle *= -1; // rotate it clockwise + } + const auto vtop2_unf = rotate(rotation_angle, normal, vtop1) * + (vtop2_len / vtop1_len); + const auto dir = vtop2_unf - vtop1; // from p1 to p2 + const auto dist = length_sq(dir); + + if(dist < distance_sq) + { + distance_sq = dist; + retval = dir; + } + } + if(distance_sq != std::numeric_limits::infinity()) + { + // distance_sq is updated! It founds the minimum path (case 1). + return retval; + } + // otherwise, there is no available direction between the positions. + throw std::runtime_error((boost::format( + ""polygon::direction: couldn't find the min path between "" + ""%1% on %2% <-> %3% on %4%"") % pos1.first % pos1.second % + pos2.first % pos2.second).str()); +} + +std::pair Polygon::travel( + const std::pair& pos, const Real3& disp) const +{ + const Real3& p = pos.first; + const FaceID f = pos.second; + const Real3 np = p + disp; + + const face_data& fd = this->face_at(f); + const Triangle& tri = fd.triangle; + const Barycentric b2(to_barycentric(np, tri)); + + // if pos + disp is inside of the current face, just return the sum. + if(::ecell4::is_inside(b2)) + { + // to avoid numerical error that make the particle goes outside of the + // face that the particle belongs, use `to_absolute`. + return std::make_pair(to_absolute(b2, tri), f); + } + + const Barycentric b1(to_barycentric(p, tri)); + const Barycentric db(b2 - b1); + const std::pair cs = first_cross_edge(b1, db); + const std::pair& next = fd.neighbor_cw[cs.first].front(); + + // if the position is inside of the adjacent face, return the position + // reconstructed from unfolded-Barycentric by using folded Triangle. + const Barycentric unfolded_b(to_barycentric(np, next.second)); + if(::ecell4::is_inside(unfolded_b, relative_tolerance)) + { + Real3 nxt = to_absolute( + force_put_inside(unfolded_b), this->triangle_at(next.first)); + + if(!this->is_inside_of_boundary(nxt)) + { + const Real xlim = this->edge_length_[0]; + const Real ylim = this->edge_length_[1]; + const Real zlim = this->edge_length_[2]; + const Real rel_tol = relative_tolerance; + + // allow numerical error in relative tolerance + if(nxt[0] < 0.0 && std::abs(nxt[0]) < rel_tol * xlim) {nxt[0] = 0.0;} + if(nxt[1] < 0.0 && std::abs(nxt[1]) < rel_tol * ylim) {nxt[1] = 0.0;} + if(nxt[2] < 0.0 && std::abs(nxt[2]) < rel_tol * zlim) {nxt[2] = 0.0;} + + if(nxt[0] > xlim && nxt[0] - xlim < rel_tol * xlim) {nxt[0] = xlim;} + if(nxt[1] > ylim && nxt[1] - ylim < rel_tol * ylim) {nxt[1] = ylim;} + if(nxt[2] > zlim && nxt[2] - zlim < rel_tol * zlim) {nxt[2] = zlim;} + + if(!this->is_inside_of_boundary(nxt)) + { + + std::cerr << ""travel: initial pos = "" << p << "" on "" << f << std::endl; + std::cerr << ""travel: initial face = "" << f << "" -> "" << this->triangle_at(f) << std::endl; + std::cerr << ""travel: initial disp = "" << disp << std::endl; + std::cerr << ""travel: next face (unfolded) = "" << next.second << std::endl; + std::cerr << ""travel: next barycentric crd = "" << unfolded_b << std::endl; + std::cerr << ""travel: next bary (inside) = "" << force_put_inside(unfolded_b) << std::endl; + std::cerr << ""travel: next face = "" << this->triangle_at(next.first) << std::endl; + std::cerr << ""travel: next pos = "" << nxt << "" on "" << next.first << std::endl; + throw std::runtime_error(""out of bound""); + } + } + return std::make_pair(nxt, next.first); + // use folded (normal) Triangle, NOT next.second + } + + // stride over not only the edge but adjacent face. + // XXX to make it sure that `on_edge` should be on the edge under the PBC, + // to_absolute is used with the next triangle. + const Barycentric on_edge_b(to_barycentric(p + disp * cs.second, next.second)); + const Real3 edge_over = direction_of(fd.edges[cs.first]); + Real3 next_pos = to_absolute(on_edge_b, this->triangle_at(next.first)); + + if(!this->is_inside_of_boundary(next_pos)) + { + const Real xlim = this->edge_length_[0]; + const Real ylim = this->edge_length_[1]; + const Real zlim = this->edge_length_[2]; + const Real rel_tol = relative_tolerance; + + // allow numerical error in relative tolerance + if(next_pos[0] < 0.0 && std::abs(next_pos[0]) < rel_tol * xlim) {next_pos[0] = 0.0;} + if(next_pos[1] < 0.0 && std::abs(next_pos[1]) < rel_tol * ylim) {next_pos[1] = 0.0;} + if(next_pos[2] < 0.0 && std::abs(next_pos[2]) < rel_tol * zlim) {next_pos[2] = 0.0;} + + if(next_pos[0] > xlim && next_pos[0] - xlim < rel_tol * xlim) {next_pos[0] = xlim;} + if(next_pos[1] > ylim && next_pos[1] - ylim < rel_tol * ylim) {next_pos[1] = ylim;} + if(next_pos[2] > zlim && next_pos[2] - zlim < rel_tol * zlim) {next_pos[2] = zlim;} + + if(!this->is_inside_of_boundary(next_pos)) + { + std::cerr << ""travel: initial pos = "" << p << "" on "" << f << std::endl; + std::cerr << ""travel: initial face = "" << f << "" -> "" << this->triangle_at(f) << std::endl; + std::cerr << ""travel: initial disp = "" << disp << std::endl; + std::cerr << ""travel: next face (unfolded) = "" << next.second << std::endl; + std::cerr << ""travel: next barycnetric (on edge) = "" << on_edge_b << std::endl; + std::cerr << ""travel: next face = "" << this->triangle_at(next.first) << std::endl; + std::cerr << ""travel: next pos = "" << next_pos << "" on "" << next.first << std::endl; + throw std::runtime_error(""out of bound""); + } + } + + return this->travel(std::make_pair(next_pos, next.first), + rotate(tilt_angle_at(fd.edges[cs.first]), // rotate disp by tilt_angle + edge_over * (1.0 / length(edge_over)), // around the edge + disp * (1 - cs.second))); // the rest of displacement +} + +std::pair Polygon::travel( + const std::pair& pos, const Real3& disp, + const std::size_t restraint) const +{ + if(restraint == 0) + { + std::cerr << ""movement along surface of a Polygon: "" + ""restraint hits 0. tolerance violated!"" << std::endl; + std::cerr << ""the rest of displacement: "" << disp << std::endl; + return pos; + } + const Real3& p = pos.first; + const FaceID f = pos.second; + const Real3 np = p + disp; + + const face_data& fd = this->face_at(f); + const Triangle& tri = fd.triangle; + const Barycentric b2(to_barycentric(np, tri)); + + // if pos + disp is inside of the current face, just return the sum. + if(::ecell4::is_inside(b2)) + { + // to avoid numerical error that make the particle goes outside of the + // face that the particle belongs, use `to_absolute`. + return std::make_pair(to_absolute(b2, tri), f); + } + + const Barycentric b1(to_barycentric(p, tri)); + const Barycentric db(b2 - b1); + const std::pair cs = first_cross_edge(b1, db); + const std::pair& next = fd.neighbor_cw[cs.first].front(); + + // if the position is inside of the adjacent face, return the position + // reconstructed from unfolded-Barycentric by using folded Triangle. + const Barycentric unfolded_b(to_barycentric(np, next.second)); + if(::ecell4::is_inside(unfolded_b, relative_tolerance)) + { + Real3 nxt = to_absolute( + force_put_inside(unfolded_b), this->triangle_at(next.first)); + + if(!this->is_inside_of_boundary(nxt)) + { + const Real xlim = this->edge_length_[0]; + const Real ylim = this->edge_length_[1]; + const Real zlim = this->edge_length_[2]; + const Real rel_tol = relative_tolerance; + + // allow numerical error in relative tolerance + if(nxt[0] < 0.0 && std::abs(nxt[0]) < rel_tol * xlim) {nxt[0] = 0.0;} + if(nxt[1] < 0.0 && std::abs(nxt[1]) < rel_tol * ylim) {nxt[1] = 0.0;} + if(nxt[2] < 0.0 && std::abs(nxt[2]) < rel_tol * zlim) {nxt[2] = 0.0;} + + if(nxt[0] > xlim && nxt[0] - xlim < rel_tol * xlim) {nxt[0] = xlim;} + if(nxt[1] > ylim && nxt[1] - ylim < rel_tol * ylim) {nxt[1] = ylim;} + if(nxt[2] > zlim && nxt[2] - zlim < rel_tol * zlim) {nxt[2] = zlim;} + + if(!this->is_inside_of_boundary(nxt)) + { + std::cerr << ""travel: initial pos = "" << p << "" on "" << f << std::endl; + std::cerr << ""travel: initial face = "" << f << "" -> "" << this->triangle_at(f) << std::endl; + std::cerr << ""travel: initial disp = "" << disp << std::endl; + std::cerr << ""travel: next face (unfolded) = "" << next.second << std::endl; + std::cerr << ""travel: next barycentric crd = "" << unfolded_b << std::endl; + std::cerr << ""travel: next bary (inside) = "" << force_put_inside(unfolded_b) << std::endl; + std::cerr << ""travel: next face = "" << this->triangle_at(next.first) << std::endl; + std::cerr << ""travel: next pos = "" << nxt << "" on "" << next.first << std::endl; + throw std::runtime_error(""particle goes exceeds the boundary""); + } + } + return std::make_pair(nxt, next.first); + // use folded (normal) Triangle, NOT next.second + } + + // stride over not only the edge but adjacent face. + // XXX to make it sure that `on_edge` should be on the edge under the PBC, + // to_absolute is used with the next triangle. + const Barycentric on_edge_b(to_barycentric(p + disp * cs.second, next.second)); + const Real3 edge_over = direction_of(fd.edges[cs.first]); + Real3 next_pos = to_absolute(on_edge_b, this->triangle_at(next.first)); + + if(!this->is_inside_of_boundary(next_pos)) + { + const Real xlim = this->edge_length_[0]; + const Real ylim = this->edge_length_[1]; + const Real zlim = this->edge_length_[2]; + const Real rel_tol = relative_tolerance; + + // allow numerical error in relative tolerance + if(next_pos[0] < 0.0 && std::abs(next_pos[0]) < rel_tol * xlim) {next_pos[0] = 0.0;} + if(next_pos[1] < 0.0 && std::abs(next_pos[1]) < rel_tol * ylim) {next_pos[1] = 0.0;} + if(next_pos[2] < 0.0 && std::abs(next_pos[2]) < rel_tol * zlim) {next_pos[2] = 0.0;} + + if(next_pos[0] > xlim && next_pos[0] - xlim < rel_tol * xlim) {next_pos[0] = xlim;} + if(next_pos[1] > ylim && next_pos[1] - ylim < rel_tol * ylim) {next_pos[1] = ylim;} + if(next_pos[2] > zlim && next_pos[2] - zlim < rel_tol * zlim) {next_pos[2] = zlim;} + + if(!this->is_inside_of_boundary(next_pos)) + { + std::cerr << ""travel: initial pos = "" << p << "" on "" << f << std::endl; + std::cerr << ""travel: initial face = "" << f << "" -> "" << this->triangle_at(f) << std::endl; + std::cerr << ""travel: initial disp = "" << disp << std::endl; + std::cerr << ""travel: next face (unfolded) = "" << next.second << std::endl; + std::cerr << ""travel: next barycnetric (on edge) = "" << on_edge_b << std::endl; + std::cerr << ""travel: next face = "" << this->triangle_at(next.first) << std::endl; + std::cerr << ""travel: next pos = "" << next_pos << "" on "" << next.first << std::endl; + throw std::runtime_error(""particle goes exceeds the boundary""); + } + } + return this->travel(std::make_pair(next_pos, next.first), + rotate(tilt_angle_at(fd.edges[cs.first]), // rotate disp by tilt_angle + edge_over * (1.0 / length(edge_over)), // around the edge + disp * (1 - cs.second)), // the rest of displacement + restraint - 1); +} + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Triangle.hpp",".hpp","4797","164","#ifndef ECELL_CORE_TRIANGLE +#define ECELL_CORE_TRIANGLE + +#include ""Shape.hpp"" +#include ""geometry.hpp"" +#include ""exceptions.hpp"" +#include ""TriangleView.hpp"" +#include ""BoundaryCondition.hpp"" + +namespace ecell4 +{ + +struct Triangle : public Shape +{ + public: + + Triangle(); + explicit Triangle(const std::array& vertices); + explicit Triangle(const TriangleView& tv); + explicit Triangle(const TriangleConstView& tv); + Triangle(const Real3& a, const Real3& b, const Real3& c); + + Triangle& operator=(const Triangle& rhs); + Triangle& operator=(const TriangleView& tv); + Triangle& operator=(const TriangleConstView& tv); + + Real3 const& normal() const + { + return normal_; + } + Real3 represent() const + { + return edges_[0] / lengths_[0]; + } + + Real3 const& vertex_at(const std::size_t i) const + { + return vertices_.at(i); + } + Real3 const& edge_at(const std::size_t i) const + { + return edges_.at(i); + } + Real const& length_of_edge_at(const std::size_t i) const + { + return lengths_.at(i); + } + Real const& angle_at(const std::size_t i) const + { + return angles_.at(i); + } + + std::array const& vertices() const + { + return vertices_; + } + std::array const& edges() const + { + return edges_; + } + std::array const& lengths_of_edges() const + { + return lengths_; + } + Real area() const + { + return 0.5 * length(cross_product(edges_[0], edges_[2] * (-1.0))); + } + + // shape + dimension_kind dimension() const + { + return TWO; + } + Real is_inside(const Real3& coord) const + { + throw NotImplemented(""Triangle::is_inside(coord)""); + } + Real3 draw_position(std::shared_ptr& rng) const + { + Real a1 = rng->uniform(0.0, 1.0); + Real a2 = rng->uniform(0.0, 1.0); + if(a1 + a2 > 1.0) + { + a1 = 1.0 - a1; + a2 = 1.0 - a2; + } + return vertices_[0] + edges_[0] * a1 - edges_[2] * a2; + } + bool test_AABB(const Real3& l, const Real3& u) const + { + throw NotImplemented(""Triangle::test_AABB(l, u)""); + } + void bounding_box( + const Real3& edge_lengths, Real3& lower, Real3& upper) const + { + const auto& v1 = this->vertices_[0]; + const auto& v2 = this->vertices_[1]; + const auto& v3 = this->vertices_[2]; + + lower[0] = std::max(0.0, std::min(std::min(v1[0], v2[0]), v3[0])); + lower[1] = std::max(0.0, std::min(std::min(v1[1], v2[1]), v3[1])); + lower[2] = std::max(0.0, std::min(std::min(v1[2], v2[2]), v3[2])); + + upper[0] = std::min(edge_lengths[0], std::max(std::max(v1[0], v2[0]), v3[0])); + upper[1] = std::min(edge_lengths[1], std::max(std::max(v1[1], v2[1]), v3[1])); + upper[2] = std::min(edge_lengths[2], std::max(std::max(v1[2], v2[2]), v3[2])); + return; + } + + private: + + Real3 normal_; + std::array lengths_; + std::array angles_; + std::array vertices_; + std::array edges_; +}; + +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri); + +inline Real distance_point_Triangle(const Real3& pos, const Triangle& tri) +{ + return std::sqrt(distance_sq_point_Triangle(pos, tri)); +} + +// ------------------------------------------------------------------------ +// considering PBC + +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri, + const Boundary& b); +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri, + const std::unique_ptr& b); +Real distance_sq_point_Triangle(const Real3& pos, const Triangle& tri, + const std::shared_ptr& b); + +inline Real distance_point_Triangle(const Real3& pos, const Triangle& tri, + const Boundary& b) +{ + return std::sqrt(distance_sq_point_Triangle(pos, tri, b)); +} +inline Real distance_point_Triangle(const Real3& pos, const Triangle& tri, + const std::unique_ptr& b) +{ + return std::sqrt(distance_sq_point_Triangle(pos, tri, b)); +} +inline Real distance_point_Triangle(const Real3& pos, const Triangle& tri, + const std::shared_ptr& b) +{ + return std::sqrt(distance_sq_point_Triangle(pos, tri, b)); +} + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const Triangle& tri) +{ + os << ""Triangle("" << tri.vertex_at(0) << "", "" << tri.vertex_at(1) << "", "" + << tri.vertex_at(2) << ')'; + return os; +} + +} // ecell +#endif /*ECELL_CORE_TRIANGLE*/ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Particle.hpp",".hpp","3746","185","#ifndef ECELL4_PARTICLE_HPP +#define ECELL4_PARTICLE_HPP + +#include +#include + +#include + +#include ""types.hpp"" +#include ""Real3.hpp"" +#include ""Species.hpp"" +#include ""Identifier.hpp"" + + +namespace ecell4 +{ + +class Particle; + +template +inline std::basic_ostream& operator<<(std::basic_ostream& strm, const Particle& p); + +class Particle +{ +public: + + typedef Real3 position_type; + typedef Real length_type; + typedef Real D_type; + typedef Species species_type; + typedef species_type::serial_type species_serial_type; + typedef std::string Location; + typedef Location location_type; + +public: + + Particle() + { + ; + } + + explicit Particle( + const Species& sp, const Real3& pos, const Real& radius, + const Real& D, const Location& loc = """") + : species_(sp), position_(pos), radius_(radius), D_(D), location_(loc) + { + ; + } + + Particle( + const species_serial_type& sid, const Real3& pos, + const Real& radius, const Real& D, const Location& loc = """") + : species_(sid), position_(pos), radius_(radius), D_(D), location_(loc) + { + ; + } + + Real3& position() + { + return position_; + } + + const Real3& position() const + { + return position_; + } + + Real& radius() + { + return radius_; + } + + const Real& radius() const + { + return radius_; + } + + Real& D() + { + return D_; + } + + const Real& D() const + { + return D_; + } + + Species& species() + { + return species_; + } + + const Species& species() const + { + return species_; + } + + Location& location() + { + return location_; + } + + const Location& location() const + { + return location_; + } + + Species::serial_type species_serial() + { + return species_.serial(); + } + + const Species::serial_type species_serial() const + { + return species_.serial(); + } + + inline Species::serial_type sid() + { + return species_serial(); + } + + inline const Species::serial_type sid() const + { + return species_serial(); + } + + bool operator==(Particle const& rhs) const + { + return (this->sid() == rhs.sid() && + this->radius() == rhs.radius() && + this->position() == rhs.position() && + this->location() == rhs.location()); + } + + bool operator!=(Particle const& rhs) const + { + return !operator==(rhs); + } + + std::string show(int precision) + { + std::ostringstream strm; + strm.precision(precision); + strm << *this; + return strm.str(); + } + +private: + + Species species_; + Real3 position_; + Real radius_, D_; + Location location_; +}; + +template +inline std::basic_ostream& operator<<(std::basic_ostream& strm, const Particle& p) +{ + strm << ""Particle("" << ""{ "" << p.position() << "", "" << p.radius() << ""}, "" << "", D="" << p.D() << "", "" << p.sid() << "", "" << p.location() << "")""; + return strm; +} + +} // ecell4 + +namespace std { + +template<> +struct hash +{ + typedef ecell4::Particle argument_type; + + std::size_t operator()(argument_type const& val) + { + return hash()(val.position()) ^ + hash()(val.radius()) ^ + hash()(val.D()) ^ + // hash()(val.species()); + hash()(val.sid()); + } +}; +} // std + +#endif /* ECELL4_PARTICLE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Rod.hpp",".hpp","1998","93","#ifndef ECELL4_ROD_HPP +#define ECELL4_ROD_HPP + +#include ""Shape.hpp"" + +namespace ecell4 +{ + +struct RodSurface; + +// A Rod is parallel with the x-axis. +// The center of a Rod is the origin. +struct Rod + : public Shape +{ +public: + + Rod(); + Rod(const Real& length, const Real& radius); + Rod(const Real& length, const Real& radius, const Real3& origin); + Rod(const Rod& rhs); + const Real& lengthX() const; + const Real& radius() const; + const Real3& origin() const; + void shift(const Real3& vec); + Real is_inside(const Real3& pos) const; + Real distance(const Real3& pos) const; + Real3 draw_position(std::shared_ptr& rng) const; + RodSurface surface() const; + bool test_AABB(const Real3& l, const Real3& u) const; + + const Real half_length() const + { + return length_ * 0.5; + } + + inline const Real& length() const + { + return lengthX(); + } + + dimension_kind dimension() const + { + return THREE; + } + +protected: + + Real length_; // LengthX + Real radius_; // LengthY/2 + Real3 origin_; +}; + +struct RodSurface + : public Shape +{ +public: + + RodSurface(); + RodSurface(const Real& length, const Real& radius); + RodSurface(const Real& length, const Real& radius, const Real3& origin); + RodSurface(const RodSurface& rhs); + const Real& lengthX() const; + const Real& radius() const; + const Real3& origin() const; + void shift(const Real3& vec); + Real is_inside(const Real3& pos) const; + Real distance(const Real3& pos) const; + Real3 draw_position(std::shared_ptr& rng) const; + Rod inside() const; + bool test_AABB(const Real3& l, const Real3& u) const; + + dimension_kind dimension() const + { + return TWO; + } + + inline const Real& length() const + { + return lengthX(); + } + +protected: + + Real length_; // LengthX + Real radius_; // LengthY/2 + Real3 origin_; // origin +}; + +} // ecell4 + +#endif /* ECELL4_ROD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Sphere.hpp",".hpp","1849","97","#ifndef ECELL4_SPHERE_HPP +#define ECELL4_SPHERE_HPP + +#include +#include ""Shape.hpp"" + +namespace ecell4 +{ + +struct SphericalSurface; + +struct Sphere + : public Shape +{ +public: + + /** for epdp + */ + typedef Real3 position_type; + typedef position_type::value_type length_type; + typedef position_type::value_type value_type; + +public: + + Sphere(); + Sphere(const Real3& center, const Real radius); + Sphere(const Sphere& rhs); + const Real& radius() const; + const Real3& center() const; + Real is_inside(const Real3& coord) const; + Real distance(const Real3& pos) const; + SphericalSurface surface() const; + Real3 draw_position( + std::shared_ptr& rng) const; + bool test_AABB(const Real3& l, const Real3& u) const; + + inline const Real3& position() const + { + return center_; + } + + Real3& position() + { + return center_; + } + + inline const Real& size() const + { + return radius_; + } + + Real& size() + { + return radius_; + } + + dimension_kind dimension() const + { + return THREE; + } + +protected: + + Real3 center_; + Real radius_; +}; + +struct SphericalSurface + : public Shape +{ + SphericalSurface(); + SphericalSurface(const Real3& center, const Real radius); + SphericalSurface(const SphericalSurface& rhs); + const Real& radius() const; + const Real3& center() const; + Real is_inside(const Real3& coord) const; + Real distance(const Real3& pos) const; + Sphere inside() const; + Real3 draw_position( + std::shared_ptr& rng) const; + bool test_AABB(const Real3& l, const Real3& u) const; + + dimension_kind dimension() const + { + return TWO; + } + +protected: + + Real3 center_; + Real radius_; +}; + +} // ecell4 + +#endif /* ECELL4_SPHERE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/EventScheduler.hpp",".hpp","3205","169","#ifndef ECELL4_EVENTSCHEDULER_HPP +#define ECELL4_EVENTSCHEDULER_HPP + +#include +#include +#include + +#include ""types.hpp"" +#include ""DynamicPriorityQueue.hpp"" + + +namespace ecell4 +{ + +struct Event +{ +public: + + Event(Real const& time) : time_(time) {} + + virtual ~Event() {} + + virtual void fire() {} + + Real const& time() const + { + return time_; + } + + //XXX: deprecate me + Real const& dt() const + { + return dt_; + } + + virtual void interrupt(Real const& t) {} + +protected: + + Real time_; + //XXX: deprecate me + Real dt_; +}; + + +template +class EventSchedulerBase +{ +protected: + + struct event_comparator + { + bool operator()(std::shared_ptr const& lhs, + std::shared_ptr const& rhs) const + { + return lhs->time() <= rhs->time(); + } + }; + + typedef DynamicPriorityQueue, event_comparator> + EventPriorityQueue; + +public: + + typedef typename EventPriorityQueue::size_type size_type; + typedef typename EventPriorityQueue::identifier_type identifier_type; + typedef typename EventPriorityQueue::value_type value_type; + typedef boost::iterator_range + events_range; + +public: + + EventSchedulerBase() : time_(0.0) {} + + ~EventSchedulerBase() {} + + Real time() const + { + return time_; + } + + size_type size() const + { + return eventPriorityQueue_.size(); + } + + value_type const& top() const + { + return eventPriorityQueue_.top(); + } + + value_type pop() + { + if (eventPriorityQueue_.empty()) + { + throw std::out_of_range(""queue is empty""); + } + const value_type top(eventPriorityQueue_.top()); + eventPriorityQueue_.pop(); + time_ = top.second->time(); + return top; + } + + value_type const& second() const + { + return eventPriorityQueue_.second(); + } + + std::shared_ptr get(identifier_type const& id) const + { + return eventPriorityQueue_.get(id); + } + + void clear() + { + time_ = 0.0; + eventPriorityQueue_.clear(); + } + + identifier_type add(std::shared_ptr const& event) + { + return eventPriorityQueue_.push(event); + } + + void remove(identifier_type const& id) + { + eventPriorityQueue_.pop(id); + } + + void update(value_type const& pair) + { + eventPriorityQueue_.replace(pair); + } + + bool check() const + { + return eventPriorityQueue_.check(); + } + + events_range events() const + { + return boost::make_iterator_range( + eventPriorityQueue_.begin(), eventPriorityQueue_.end()); + } + + const Real next_time() const + { + if (size() > 0) + { + return top().second->time(); + } + else + { + return std::numeric_limits::infinity(); + } + } + +protected: + + EventPriorityQueue eventPriorityQueue_; + Real time_; +}; + +typedef EventSchedulerBase EventScheduler; + +} // ecell4 + +#endif /* ECELL4_EVENTSCHEDULER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/HCPLatticeSpace.cpp",".cpp","1535","55","#include ""HCPLatticeSpace.hpp"" + +#include + +#ifdef WIN32_MSC +#include +#endif + +namespace ecell4 +{ + +#ifdef WIN32_MSC +double rint(const double x) +{ + return boost::numeric::interval_lib::detail::rint(x); +} + +double round(const double x) { return floor(x + 0.5); } +#endif + +void HCPLatticeSpace::set_lattice_properties(const Real3 &edge_lengths, + const bool is_periodic) +{ + // XXX: derived from SpatiocyteStepper::setLatticeProperties() + HCP_L = voxel_radius_ / sqrt(3.0); + HCP_X = voxel_radius_ * sqrt(8.0 / 3.0); // Lx + HCP_Y = voxel_radius_ * sqrt(3.0); // Ly + + const Real &lengthX = edge_lengths[0]; + const Real &lengthY = edge_lengths[1]; + const Real &lengthZ = edge_lengths[2]; + + col_size_ = (Integer)rint(lengthX / HCP_X); + layer_size_ = (Integer)rint(lengthY / HCP_Y); + row_size_ = (Integer)rint((lengthZ / 2) / voxel_radius_); + + if (is_periodic) + { + // The number of voxels in each axis must be even for a periodic + // boundary. + col_size_ = (col_size_ % 2 == 0 ? col_size_ : col_size_ + 1); + layer_size_ = (layer_size_ % 2 == 0 ? layer_size_ : layer_size_ + 1); + row_size_ = (row_size_ % 2 == 0 ? row_size_ : row_size_ + 1); + } + + edge_lengths_ = Real3(col_size_ * HCP_X, layer_size_ * HCP_Y, + row_size_ * voxel_radius_ * 2); + + row_size_ += 2; + layer_size_ += 2; + col_size_ += 2; +} + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Species.hpp",".hpp","3352","131","#ifndef ECELL4_SPECIES_HPP +#define ECELL4_SPECIES_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// #include + +#include + +#include ""types.hpp"" +#include ""exceptions.hpp"" +#include ""UnitSpecies.hpp"" +// #include ""Context.hpp"" +#include ""Quantity.hpp"" +#include ""Attribute.hpp"" + + +namespace ecell4 +{ + +class Species +{ +public: + + typedef UnitSpecies::serial_type serial_type; //XXX: std::string + typedef std::vector container_type; + +public: + + typedef Attribute::mapped_type attribute_type; + +public: + + Species(); + explicit Species(const serial_type& name); + Species(const Species& another); + Species& operator=(const Species& another); + Species(const serial_type& name, const Real& radius, const Real& D, + const std::string location = """", const Integer& dimension = 0); + Species(const serial_type& name, const Quantity& radius, const Quantity& D, + const std::string location = """", const Integer& dimension = 0); + + const serial_type serial() const; + + void add_unit(const UnitSpecies& usp); + const std::vector units() const; + + const Attribute& attributes() const; + + std::vector > list_attributes() const; + attribute_type get_attribute(const std::string& key) const; + + template + T_ get_attribute_as(const std::string& key) const + { + return attributes_.get_as(key); + } + + template + void set_attribute(const std::string& key, T_ value) + { + attributes_.set(key, value); + } + + void set_attributes(const Attribute& attributes); + void set_attributes(const Species& sp); + void remove_attribute(const std::string& key); + bool has_attribute(const std::string& key) const; + void overwrite_attributes(const Species& sp); + + bool operator==(const Species& rhs) const; + bool operator!=(const Species& rhs) const; + bool operator<(const Species& rhs) const; + bool operator>(const Species& rhs) const; + + Integer count(const Species& sp) const; + + /** Method chaining + */ + + Species& D(const std::string& value); + Species* D_ptr(const std::string& value); + Species& radius(const std::string& value); + Species* radius_ptr(const std::string& value); + Species& location(const std::string& value); + Species* location_ptr(const std::string& value); + Species& dimension(const std::string& value); + Species* dimension_ptr(const std::string& value); + + /** for epdp + */ + serial_type name() const; + +protected: + + serial_type serial_; + Attribute attributes_; +}; + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& strm, + const ecell4::Species& sp) +{ + strm << sp.serial(); + return strm; +} + +} // ecell4 + +namespace std { +template<> +struct hash +{ + std::size_t operator()(const ecell4::Species& val) const + { + return hash()(val.serial()); + } +}; +} // std + +#endif /* ECELL4_SPECIES_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Integer3.hpp",".hpp","3999","181","#ifndef ECELL4_INTEGER3_HPP +#define ECELL4_INTEGER3_HPP + +#include +#include +#include + +#include ""types.hpp"" +#include ""exceptions.hpp"" +#include ""functions.hpp"" + + +namespace ecell4 +{ + +struct Integer3 +{ + typedef Integer value_type; + typedef std::size_t size_type; + + value_type col; + value_type row; + value_type layer; + + Integer3() + { + this->col = 0; + this->row = 0; + this->layer = 0; + } + + Integer3(value_type col, value_type row, value_type layer) + { + this->col = col; + this->row = row; + this->layer = layer; + } + + Integer3(const Integer3& global) + { + this->col = global.col; + this->row = global.row; + this->layer = global.layer; + } + + Integer3 east() const; + Integer3 west() const; + Integer3 south() const; + Integer3 north() const; + Integer3 dorsal() const; + Integer3 ventral() const; + + Integer3& operator+=(const Integer3& rhs); + Integer3& operator-=(const Integer3& rhs); + Integer3& operator*=(const Integer3::value_type& rhs); + + value_type& operator[](size_type i) + { + switch (i) + { + case 0: + return this->col; + case 1: + return this->row; + case 2: + return this->layer; + } + throw std::out_of_range(""""); + } + + const value_type& operator[](size_type i) const + { + switch (i) + { + case 0: + return this->col; + case 1: + return this->row; + case 2: + return this->layer; + } + throw std::out_of_range(""""); + } +}; + +inline Integer3 add(const Integer3& g1, const Integer3& g2) +{ + Integer3 retval; + retval.col = g1.col + g2.col; + retval.row = g1.row + g2.row; + retval.layer = g1.layer + g2.layer; + return retval; +} + +inline Integer3 subtract(const Integer3& g1, const Integer3& g2) +{ + Integer3 retval; + retval.col = g1.col - g2.col; + retval.row = g1.row - g2.row; + retval.layer = g1.layer - g2.layer; + return retval; +} + +inline Integer3 abs(const Integer3& g1) +{ + Integer3 retval; + retval.col = abs(g1.col); + retval.row = abs(g1.row); + retval.layer = abs(g1.layer); + return retval; +} + +inline Integer3 multiply(const Integer3& p1, const Integer3::value_type& p2) +{ + Integer3 retval; + retval[0] = p1[0] * p2; + retval[1] = p1[1] * p2; + retval[2] = p1[2] * p2; + return retval; +} + +inline Integer3::value_type length_sq(const Integer3& r) +{ + return pow_2(r[0]) + pow_2(r[1]) + pow_2(r[2]); +} + +inline Real length(const Integer3& r) +{ + return std::sqrt(static_cast(length_sq(r))); +} + +inline Integer3::value_type dot_product( + const Integer3& p1, const Integer3& p2) +{ + return p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]; +} + +inline Integer3 operator+(const Integer3& lhs, const Integer3& rhs) +{ + return add(lhs, rhs); +} + +inline Integer3 operator-(const Integer3& lhs, const Integer3& rhs) +{ + return subtract(lhs, rhs); +} + +inline bool operator<(const Integer3& lhs, const Integer3& rhs) +{ + return (lhs.col < rhs.col ? true : + (lhs.row < rhs.row ? true : (lhs.layer < rhs.layer ? true : false))); +} + +inline bool operator>(const Integer3& lhs, const Integer3& rhs) +{ + return (lhs.col > rhs.col ? true : + (lhs.row > rhs.row ? true : (lhs.layer > rhs.layer ? true : false))); +} + +inline bool operator==(const Integer3& lhs, const Integer3& rhs) +{ + return (lhs.col == rhs.col && lhs.row == rhs.row && lhs.layer == rhs.layer); +} + +inline bool operator!=(const Integer3& lhs, const Integer3& rhs) +{ + return (lhs.col != rhs.col || lhs.row != rhs.row || lhs.layer != rhs.layer); +} + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& strm, const Integer3& g) +{ + strm << ""{"" << g.col << "", "" << g.row << "", "" << g.layer << ""}""; + return strm; +} + +} // ecell4 + +#endif /* ECELL4_INTEGER3_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/Cylinder.cpp",".cpp","2794","143","#include ""Cylinder.hpp"" +#include ""exceptions.hpp"" +#include ""collision.hpp"" + + +namespace ecell4 +{ + +Cylinder::Cylinder() + : center_(), radius_(), axis_(), half_height_() +{ + ; +} + +Cylinder::Cylinder(const Real3& center, const Real radius, + const Real3& axis, const Real half_height) + : center_(center), radius_(radius), axis_(axis), half_height_(half_height) +{ + ; +} + +Cylinder::Cylinder(const Cylinder& rhs) + : center_(rhs.center()), radius_(rhs.radius()), + axis_(rhs.axis()), half_height_(rhs.half_height_) +{ + ; +} + +const Real& Cylinder::radius() const +{ + return radius_; +} + +const Real3& Cylinder::center() const +{ + return center_; +} + +const Real& Cylinder::half_height() const +{ + return half_height_; +} + +const Real3& Cylinder::axis() const +{ + return axis_; +} + +Real Cylinder::distance(const Real3& coord) const +{ + return collision::distance_point_cylinder(coord, *this); +} + +Real Cylinder::is_inside(const Real3& coord) const +{ + return distance(coord); +} + +CylindricalSurface Cylinder::surface() const +{ + return CylindricalSurface(center_, radius_, axis_, half_height_); +} + +Real3 Cylinder::draw_position( + std::shared_ptr& rng) const +{ + throw NotImplemented(""not implemented yet.""); +} + +bool Cylinder::test_AABB(const Real3& l, const Real3& u) const +{ + throw NotImplemented(""not implemented yet.""); +} + +CylindricalSurface::CylindricalSurface() + : center_(), radius_(), axis_(), half_height_() +{ + ; +} + +CylindricalSurface::CylindricalSurface(const Real3& center, const Real radius, + const Real3& axis, const Real half_height) + : center_(center), radius_(radius), axis_(axis), half_height_(half_height) +{ + ; +} + +CylindricalSurface::CylindricalSurface(const CylindricalSurface& rhs) + : center_(rhs.center()), radius_(rhs.radius()), + axis_(rhs.axis()), half_height_(rhs.half_height_) +{ + ; +} + +const Real& CylindricalSurface::radius() const +{ + return radius_; +} + +const Real3& CylindricalSurface::center() const +{ + return center_; +} + +const Real& CylindricalSurface::half_height() const +{ + return half_height_; +} + +const Real3& CylindricalSurface::axis() const +{ + return axis_; +} + +Real CylindricalSurface::distance(const Real3& coord) const +{ + return inside().distance(coord); //XXX: This is too slow. +} + +Real CylindricalSurface::is_inside(const Real3& coord) const +{ + return distance(coord); +} + +Cylinder CylindricalSurface::inside() const +{ + return Cylinder(center_, radius_, axis_, half_height_); +} + +Real3 CylindricalSurface::draw_position( + std::shared_ptr& rng) const +{ + throw NotImplemented(""not implemented yet.""); +} + +bool CylindricalSurface::test_AABB(const Real3& l, const Real3& u) const +{ + throw NotImplemented(""not implemented yet.""); +} + +} // ecell4 + +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/OffLatticeSpace_test.cpp",".cpp","5790","172","#define BOOST_TEST_MODULE ""OffLatticeSpace_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +#include +#else +#define BOOST_TEST_NO_LIB +#include +#endif + +#include + +#include +#include + +using namespace ecell4; + +struct Fixture +{ + const Real voxel_radius; + const Species base; + const Species species; + const OffLatticeSpace::coordinate_type coordinate; + OffLatticeSpace space; + SerialIDGenerator sidgen; + + Fixture() + : voxel_radius(2.5e-9), base(/* serial = */ ""Base"", + /* radius = */ 2.5e-9, + /* D = */ 1e-12), + species(/* serial = */ ""SpeciesA"", + /* radius = */ 2.5e-9, + /* D = */ 1e-12, + /* location = */ ""Base""), + coordinate(3), space(voxel_radius, base) + { + OffLatticeSpace::position_container positions; + const Real unit(voxel_radius / sqrt(3.0)); + for (int i(0); i < 10; ++i) + positions.push_back(Real3(unit * i, unit * i, unit * i)); + OffLatticeSpace::coordinate_pair_list_type adjoining_pairs; + for (int i(1); i < 10; ++i) + adjoining_pairs.push_back(std::make_pair(i - 1, i)); + space = OffLatticeSpace(voxel_radius, base, positions, adjoining_pairs); + space.make_molecular_type(species, ""Base""); + } +}; + +BOOST_FIXTURE_TEST_SUITE(suite, Fixture) + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_constructor) {} + +BOOST_AUTO_TEST_CASE(CheckVacantSize) +{ + BOOST_CHECK_EQUAL(space.actual_size(), space.vacant()->size()); +} + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_molecules) +{ + const ParticleID pid(sidgen()); + space.update_voxel(pid, species, coordinate); + + BOOST_CHECK_EQUAL(space.num_molecules(species), 1); +} + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_voxelspacebase) +{ + const ParticleID pid(sidgen()); + space.update_voxel(pid, species, coordinate); + + BOOST_CHECK_EQUAL(space.list_species().size(), 1); + BOOST_CHECK_EQUAL(space.num_voxels_exact(species), 1); + BOOST_CHECK_EQUAL(space.num_voxels(species), 1); + BOOST_CHECK_EQUAL(space.num_voxels(), 10); + + BOOST_CHECK(space.has_voxel(pid)); + BOOST_CHECK(!space.has_voxel(sidgen())); + + BOOST_CHECK_EQUAL(space.list_voxels().size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels(species).size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels_exact(species).size(), 1); + + BOOST_CHECK_EQUAL(space.list_voxels().at(0).pid, pid); + BOOST_CHECK_EQUAL(space.list_voxels(species).at(0).pid, pid); + BOOST_CHECK_EQUAL(space.list_voxels_exact(species).at(0).pid, pid); + + BOOST_CHECK_NO_THROW(space.find_voxel_pool(species)); + BOOST_CHECK(space.has_molecule_pool(species)); + BOOST_CHECK_NO_THROW(space.find_molecule_pool(species)); +} + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_voxel) +{ + const ParticleID pid(sidgen()); + + BOOST_CHECK(!space.has_voxel(pid)); + BOOST_CHECK(space.update_voxel(pid, species, coordinate)); + + BOOST_CHECK(space.has_voxel(pid)); + BOOST_CHECK(space.remove_voxel(pid)); + + BOOST_CHECK(!space.has_voxel(pid)); + BOOST_CHECK(!space.remove_voxel(3)); + + BOOST_CHECK(!space.has_voxel(pid)); + BOOST_CHECK(space.update_voxel(pid, species, coordinate)); + + BOOST_CHECK(space.has_voxel(pid)); + BOOST_CHECK(space.remove_voxel(3)); + + BOOST_CHECK(!space.has_voxel(pid)); + BOOST_CHECK(!space.remove_voxel(pid)); +} + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_move) +{ + const ParticleID pid(sidgen()); + BOOST_CHECK(space.update_voxel(pid, species, coordinate)); + + BOOST_CHECK(space.can_move(3, 4)); + BOOST_CHECK(space.move(3, 4, 0)); + BOOST_CHECK_EQUAL(space.get_voxel_at(3).pid, ParticleID()); + BOOST_CHECK_EQUAL(space.get_voxel_at(4).pid, pid); + + BOOST_CHECK(!space.can_move(3, 4)); +} + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_at) +{ + BOOST_CHECK_EQUAL(space.size(), 10); + + const ParticleID pid(sidgen()); + BOOST_CHECK(space.update_voxel(pid, species, coordinate)); + + BOOST_CHECK_NO_THROW(space.get_voxel_at(3)); + BOOST_CHECK_EQUAL(space.get_voxel_at(3).pid, pid); +} + +BOOST_AUTO_TEST_CASE(OffLatticeSpace_test_neighbor) +{ + BOOST_CHECK_EQUAL(space.num_neighbors(0), 1); + BOOST_CHECK_EQUAL(space.num_neighbors(1), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(2), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(3), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(4), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(5), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(6), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(7), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(8), 2); + BOOST_CHECK_EQUAL(space.num_neighbors(9), 1); + + BOOST_CHECK_EQUAL(space.get_neighbor(0, 0), 1); + BOOST_CHECK_EQUAL(space.get_neighbor(1, 0), 0); + BOOST_CHECK_EQUAL(space.get_neighbor(1, 1), 2); + BOOST_CHECK_EQUAL(space.get_neighbor(2, 0), 1); + BOOST_CHECK_EQUAL(space.get_neighbor(2, 1), 3); + BOOST_CHECK_EQUAL(space.get_neighbor(3, 0), 2); + BOOST_CHECK_EQUAL(space.get_neighbor(3, 1), 4); + BOOST_CHECK_EQUAL(space.get_neighbor(4, 0), 3); + BOOST_CHECK_EQUAL(space.get_neighbor(4, 1), 5); + BOOST_CHECK_EQUAL(space.get_neighbor(5, 0), 4); + BOOST_CHECK_EQUAL(space.get_neighbor(5, 1), 6); + BOOST_CHECK_EQUAL(space.get_neighbor(6, 0), 5); + BOOST_CHECK_EQUAL(space.get_neighbor(6, 1), 7); + BOOST_CHECK_EQUAL(space.get_neighbor(7, 0), 6); + BOOST_CHECK_EQUAL(space.get_neighbor(7, 1), 8); + BOOST_CHECK_EQUAL(space.get_neighbor(8, 0), 7); + BOOST_CHECK_EQUAL(space.get_neighbor(8, 1), 9); + BOOST_CHECK_EQUAL(space.get_neighbor(9, 0), 8); +} + +BOOST_AUTO_TEST_SUITE_END() +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/SubvolumeSpace_test.cpp",".cpp","2445","71","#define BOOST_TEST_MODULE ""SubvolumeSpace_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include + +using namespace ecell4; + +template +void SubvolumeSpace_test_volume_template() +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(2, 3, 4); + Timpl_ target(edge_lengths, matrix_sizes); + + BOOST_CHECK_CLOSE(target.volume(), 1e-18, 1e-6); + BOOST_CHECK_EQUAL(target.num_subvolumes(), 24); + BOOST_CHECK_CLOSE(target.subvolume(), 4.166666666666667e-20, 1e-6); + + BOOST_CHECK_EQUAL(target.global2coord(Integer3()), 0); + BOOST_CHECK_EQUAL(target.global2coord(Integer3(1, 0, 0)), 1); + BOOST_CHECK_EQUAL(target.global2coord(Integer3(1, 2, 3)), 23); + BOOST_CHECK_EQUAL(target.coord2global(0), Integer3(0, 0, 0)); + BOOST_CHECK_EQUAL(target.coord2global(1), Integer3(1, 0, 0)); + BOOST_CHECK_EQUAL(target.coord2global(23), Integer3(1, 2, 3)); +} + +BOOST_AUTO_TEST_CASE(SubvolumeSpace_test_volume) +{ + SubvolumeSpace_test_volume_template(); +} + +template +void SubvolumeSpace_test_num_molecules_template() +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(2, 3, 4); + Timpl_ target(edge_lengths, matrix_sizes); + + const Species sp1(""A""), sp2(""B""); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp1, 0), 0); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp1, 23), 0); + target.reserve_pool(sp1, 0.0, """"); + target.add_molecules(sp1, 60, 0); + target.remove_molecules(sp1, 30, 0); + target.add_molecules(sp1, 60, 23); + target.reserve_pool(sp2, 0.0, """"); + target.add_molecules(sp2, 60, 23); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp1, 0), 30); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp2, 0), 0); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp1, 23), 60); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp2, 23), 60); + + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp1), 90); + BOOST_CHECK_EQUAL(target.num_molecules_exact(sp2), 60); + BOOST_CHECK_EQUAL(target.num_molecules(Species(""_"")), 150); +} + +BOOST_AUTO_TEST_CASE(SubvolumeSpace_test_num_molecules) +{ + SubvolumeSpace_test_num_molecules_template(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/EventScheduler_test.cpp",".cpp","434","20","#define BOOST_TEST_MODULE ""EventScheduler_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include + +using namespace ecell4; + +BOOST_AUTO_TEST_CASE(EventScheduler_test_constructor) +{ + EventScheduler scheduler; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/Polygon_test.cpp",".cpp","66693","1720","#define BOOST_TEST_MODULE ""Polygon_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include +#include +#include + +using ecell4::Real; +using ecell4::Real3; +using ecell4::Triangle; +using ecell4::RandomNumberGenerator; +using ecell4::GSLRandomNumberGenerator; +typedef ecell4::FaceID FaceID; +typedef ecell4::EdgeID EdgeID; +typedef ecell4::VertexID VertexID; + +bool check_equal(const Real3& lhs, const Real3& rhs, const Real tol) +{ + return std::abs(lhs[0] - rhs[0]) < tol && + std::abs(lhs[1] - rhs[1]) < tol && + std::abs(lhs[2] - rhs[2]) < tol; +} + +namespace ecell +{ +// Q1. Why is this here? use boost::algorithm or c++11 is_permutation. +// A1. Boost 1.54 (Travis.CI default) uses boost/tr1/tuple to use std::tr1::tie +// in boost::algorithm::is_permutation. But ecell4 uses through +// , and each library(GCC C++ standard library and Boost) has +// its original implementation for std::tr1::tuple. It cause multiple-definition +// problem! To avoid this, impelement is_permutation without std::tr1::tuple. +// +// Q2. Why is this in the `ecell` namespace? +// A2. If the environment has c++11 standard library, std::is_permutation become +// a candidate because of the ADL. The argument will be a std::vector::iterator, +// and std::is_permutation is found in the `std` namespace. To avoid this +// ambiguity, put it in the namespace ecell. +template +bool is_permutation(const Iterator1 first1, const Iterator1 last1, + const Iterator2 first2, const Iterator2 last2) +{ + if(std::distance(first1, last1) != std::distance(first2, last2)) + { + return false; + } + if(first1 == last1) {return true;} + + for(Iterator1 i(first1); i != last1; ++i) + { + const std::size_t num_in_1 = std::count(first1, last1, *i); + const std::size_t num_in_2 = std::count(first2, last2, *i); + if(num_in_1 != num_in_2) {return false;} + } + return true; +} +} // detail + +//! test data 1: tetrahedron +// below, the normal vector towords the depth of your display. +// +// _4 +// 3__--- / +// /|\ 4 / +// /3|1\ / +// /__|__\/ +//4 1| /2 +// |2/ +// |/ +// 4 +// +// p1 = {0, 0, 0} +// p2 = {1, 0, 0} +// p3 = {0, 1, 0} +// p4 = {0, 0, 1} +struct tetrahedron +{ + const static Real3 p1; + const static Real3 p2; + const static Real3 p3; + const static Real3 p4; + + static ecell4::Polygon make() + { + const Triangle t1(p1, p2, p4); + const Triangle t2(p1, p4, p3); + const Triangle t3(p1, p3, p2); + const Triangle t4(p2, p3, p4); + + std::vector triangles; + triangles.push_back(t1); + triangles.push_back(t2); + triangles.push_back(t3); + triangles.push_back(t4); + + return ecell4::Polygon(Real3(10.0, 10.0, 10.0), triangles); + } +}; +const Real3 tetrahedron::p1 = Real3(0, 0, 0); +const Real3 tetrahedron::p2 = Real3(1, 0, 0); +const Real3 tetrahedron::p3 = Real3(0, 1, 0); +const Real3 tetrahedron::p4 = Real3(0, 0, 1); + +BOOST_AUTO_TEST_CASE(Polygon_tetrahedron_construction_from_triangles) +{ + const Real pi = boost::math::constants::pi(); + const ecell4::Polygon poly = tetrahedron::make(); + + // check shape detection + BOOST_CHECK_EQUAL(poly.face_size(), 4u); + BOOST_CHECK_EQUAL(poly.edge_size(), 6u * 2u); + BOOST_CHECK_EQUAL(poly.vertex_size(), 4u); + BOOST_CHECK_CLOSE(poly.total_area(), 1.5 + std::sqrt(3) / 2, 1e-8); + + // check vertex position + BOOST_CHECK(static_cast(poly.find_vertex(tetrahedron::p1))); + BOOST_CHECK(static_cast(poly.find_vertex(tetrahedron::p2))); + BOOST_CHECK(static_cast(poly.find_vertex(tetrahedron::p3))); + BOOST_CHECK(static_cast(poly.find_vertex(tetrahedron::p4))); + + const VertexID v1 = *poly.find_vertex(tetrahedron::p1); + const VertexID v2 = *poly.find_vertex(tetrahedron::p2); + const VertexID v3 = *poly.find_vertex(tetrahedron::p3); + const VertexID v4 = *poly.find_vertex(tetrahedron::p4); + + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v1), tetrahedron::p1) - + tetrahedron::p1), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v2), tetrahedron::p2) - + tetrahedron::p2), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v3), tetrahedron::p3) - + tetrahedron::p3), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v4), tetrahedron::p4) - + tetrahedron::p4), 1e-8); + + // check apex angle + BOOST_CHECK_CLOSE(poly.apex_angle_at(v1), 1.5 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v2), 5.0/6.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v3), 5.0/6.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v4), 5.0/6.0 * pi, 1e-8); + + // check all the outgoing_edges are terminated at the correct vertex. + { + const std::vector ans = boost::assign::list_of(v2)(v3)(v4); + + std::vector result; result.reserve(3); + const std::vector es = poly.outgoing_edges(v1); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + { + const std::vector ans = boost::assign::list_of(v1)(v3)(v4); + + std::vector result; result.reserve(3); + const std::vector es = poly.outgoing_edges(v2); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + { + const std::vector ans = boost::assign::list_of(v1)(v2)(v4); + + std::vector result; result.reserve(3); + const std::vector es = poly.outgoing_edges(v3); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + { + const std::vector ans = boost::assign::list_of(v1)(v2)(v3); + + std::vector result; result.reserve(3); + const std::vector es = poly.outgoing_edges(v4); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + + // check all the vertex are in contact with the correct set of faces. + { + const std::vector ans = boost::assign::list_of(v1)(v2)(v3); + + std::vector result; result.reserve(3); + const std::vector es = poly.outgoing_edges(v4); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + + // check all the edges exist and has correct next-edge + BOOST_CHECK(static_cast(poly.find_edge(v1, v2))); + BOOST_CHECK(static_cast(poly.find_edge(v1, v3))); + BOOST_CHECK(static_cast(poly.find_edge(v1, v4))); + BOOST_CHECK(static_cast(poly.find_edge(v2, v1))); + BOOST_CHECK(static_cast(poly.find_edge(v2, v3))); + BOOST_CHECK(static_cast(poly.find_edge(v2, v4))); + BOOST_CHECK(static_cast(poly.find_edge(v3, v1))); + BOOST_CHECK(static_cast(poly.find_edge(v3, v2))); + BOOST_CHECK(static_cast(poly.find_edge(v3, v4))); + BOOST_CHECK(static_cast(poly.find_edge(v4, v1))); + BOOST_CHECK(static_cast(poly.find_edge(v4, v2))); + BOOST_CHECK(static_cast(poly.find_edge(v4, v3))); + + const EdgeID e12 = *poly.find_edge(v1, v2); + const EdgeID e13 = *poly.find_edge(v1, v3); + const EdgeID e14 = *poly.find_edge(v1, v4); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e12))), v1); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e13))), v1); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e14))), v1); + + const EdgeID e21 = *poly.find_edge(v2, v1); + const EdgeID e23 = *poly.find_edge(v2, v3); + const EdgeID e24 = *poly.find_edge(v2, v4); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e21))), v2); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e23))), v2); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e24))), v2); + + const EdgeID e31 = *poly.find_edge(v3, v1); + const EdgeID e32 = *poly.find_edge(v3, v2); + const EdgeID e34 = *poly.find_edge(v3, v4); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e31))), v3); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e32))), v3); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e34))), v3); + + const EdgeID e41 = *poly.find_edge(v4, v1); + const EdgeID e42 = *poly.find_edge(v4, v2); + const EdgeID e43 = *poly.find_edge(v4, v3); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e41))), v4); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e42))), v4); + BOOST_CHECK_EQUAL(poly.target_of(poly.next_of(poly.next_of(e43))), v4); + + // check opposite edges + BOOST_CHECK_EQUAL(poly.opposite_of(e12), e21); + BOOST_CHECK_EQUAL(poly.opposite_of(e13), e31); + BOOST_CHECK_EQUAL(poly.opposite_of(e14), e41); + + BOOST_CHECK_EQUAL(poly.opposite_of(e21), e12); + BOOST_CHECK_EQUAL(poly.opposite_of(e23), e32); + BOOST_CHECK_EQUAL(poly.opposite_of(e24), e42); + + BOOST_CHECK_EQUAL(poly.opposite_of(e31), e13); + BOOST_CHECK_EQUAL(poly.opposite_of(e32), e23); + BOOST_CHECK_EQUAL(poly.opposite_of(e34), e43); + + BOOST_CHECK_EQUAL(poly.opposite_of(e41), e14); + BOOST_CHECK_EQUAL(poly.opposite_of(e42), e24); + BOOST_CHECK_EQUAL(poly.opposite_of(e43), e34); + + // check face ids + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e12)), poly.face_of(e12)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e12))), poly.face_of(e12)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e13)), poly.face_of(e13)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e13))), poly.face_of(e13)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e14)), poly.face_of(e14)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e14))), poly.face_of(e14)); + + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e21)), poly.face_of(e21)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e21))), poly.face_of(e21)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e23)), poly.face_of(e23)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e23))), poly.face_of(e23)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e24)), poly.face_of(e24)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e24))), poly.face_of(e24)); + + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e31)), poly.face_of(e31)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e31))), poly.face_of(e31)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e32)), poly.face_of(e32)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e32))), poly.face_of(e32)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e34)), poly.face_of(e34)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e34))), poly.face_of(e34)); + + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e41)), poly.face_of(e41)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e41))), poly.face_of(e41)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e42)), poly.face_of(e42)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e42))), poly.face_of(e42)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of( e43)), poly.face_of(e43)); + BOOST_CHECK_EQUAL(poly.face_of(poly.next_of(poly.next_of(e43))), poly.face_of(e43)); + + BOOST_CHECK(check_equal(poly.direction_of(e12), poly.periodic_transpose( + poly.position_at(v2), poly.position_at(v1)) - poly.position_at(v1), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e13), poly.periodic_transpose( + poly.position_at(v3), poly.position_at(v1)) - poly.position_at(v1), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e14), poly.periodic_transpose( + poly.position_at(v4), poly.position_at(v1)) - poly.position_at(v1), 1e-8)); + + BOOST_CHECK(check_equal(poly.direction_of(e21), poly.periodic_transpose( + poly.position_at(v1), poly.position_at(v2)) - poly.position_at(v2), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e23), poly.periodic_transpose( + poly.position_at(v3), poly.position_at(v2)) - poly.position_at(v2), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e24), poly.periodic_transpose( + poly.position_at(v4), poly.position_at(v2)) - poly.position_at(v2), 1e-8)); + + BOOST_CHECK(check_equal(poly.direction_of(e31), poly.periodic_transpose( + poly.position_at(v1), poly.position_at(v3)) - poly.position_at(v3), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e32), poly.periodic_transpose( + poly.position_at(v2), poly.position_at(v3)) - poly.position_at(v3), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e34), poly.periodic_transpose( + poly.position_at(v4), poly.position_at(v3)) - poly.position_at(v3), 1e-8)); + + BOOST_CHECK(check_equal(poly.direction_of(e41), poly.periodic_transpose( + poly.position_at(v1), poly.position_at(v4)) - poly.position_at(v4), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e42), poly.periodic_transpose( + poly.position_at(v2), poly.position_at(v4)) - poly.position_at(v4), 1e-8)); + BOOST_CHECK(check_equal(poly.direction_of(e43), poly.periodic_transpose( + poly.position_at(v3), poly.position_at(v4)) - poly.position_at(v4), 1e-8)); + + + // test of distance + const FaceID f1 = *(poly.find_face(v1, v2, v3)); + const FaceID f2 = *(poly.find_face(v1, v2, v4)); + const FaceID f3 = *(poly.find_face(v1, v3, v4)); + const FaceID f4 = *(poly.find_face(v2, v3, v4)); + { + const Real3 p1(0, 0, 0); + const Real3 p2(0, 0, 1); + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f1), std::make_pair(p2, f2)), + 1.0, 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f2), std::make_pair(p1, f1)), + 1.0, 1e-8); + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f1), std::make_pair(p2, f3)), + 1.0, 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f3), std::make_pair(p1, f1)), + 1.0, 1e-8); + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f1), std::make_pair(p2, f4)), + 1.0, 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f4), std::make_pair(p1, f1)), + 1.0, 1e-8); + } + + { + const Real3 p1(1.0/3.0, 1.0/3.0, 0); + const Real3 p2(1.0/3.0, 1.0/3.0, 1.0/3.0); + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f1), std::make_pair(p2, f4)), + (std::sqrt(2) + std::sqrt(6)) / 6.0, 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f4), std::make_pair(p1, f1)), + (std::sqrt(2) + std::sqrt(6)) / 6.0, 1e-8); + + } + + { + std::shared_ptr rng = std::make_shared(12345); + for(std::size_t i=0; i<1000; ++i) + { + FaceID f1, f2; + const Real3 p1 = poly.draw_position(rng, f1); + const Real3 p2 = poly.draw_position(rng, f2); + + const Real d_3d = length(poly.periodic_transpose(p1, p2) - p2); + const Real d_2d = ::ecell4::polygon::distance(poly, std::make_pair(p1, f1), std::make_pair(p2, f2)); + BOOST_CHECK(d_2d >= d_3d); + } + } +} + +//! test data 2: octahedron +// below, the normal vector towords the depth of your display. +// 3 +// ^ +// / \ +// / 2 \ +// 3______1/_____\4______3 +// \ /\ /\ /\ +// \ 1 / \ 3 / \ 7 / \ +// \ / 4 \ / 6 \ / 8 \ +// v______v______v______\ +// 2 5\ /6 2 +// \ 5 / +// \ / +// v +// 2 +// p1 = {1, 1, 2} +// p2 = {2, 1, 1} +// p3 = {1, 2, 1} +// p4 = {0, 1, 1} +// p5 = {1, 0, 1} +// p6 = {1, 1, 0} +struct octahedron +{ + const static Real3 p1; + const static Real3 p2; + const static Real3 p3; + const static Real3 p4; + const static Real3 p5; + const static Real3 p6; + + static ecell4::Polygon make() + { + const Triangle t1(p1, p2, p3); + const Triangle t3(p1, p4, p5); + const Triangle t4(p1, p3, p4); + const Triangle t2(p1, p5, p2); + + const Triangle t5(p6, p5, p4); + const Triangle t6(p6, p4, p3); + const Triangle t7(p6, p3, p2); + const Triangle t8(p6, p2, p5); + + std::vector triangles; + triangles.push_back(t1); + triangles.push_back(t2); + triangles.push_back(t3); + triangles.push_back(t4); + + triangles.push_back(t5); + triangles.push_back(t6); + triangles.push_back(t7); + triangles.push_back(t8); + + return ecell4::Polygon(Real3(10.0, 10.0, 10.0), triangles); + } +}; +const Real3 octahedron::p1 = Real3(1, 1, 2); +const Real3 octahedron::p2 = Real3(2, 1, 1); +const Real3 octahedron::p3 = Real3(1, 2, 1); +const Real3 octahedron::p4 = Real3(0, 1, 1); +const Real3 octahedron::p5 = Real3(1, 0, 1); +const Real3 octahedron::p6 = Real3(1, 1, 0); + +BOOST_AUTO_TEST_CASE(Polygon_octahedron_construction_from_triangles) +{ + const Real pi = boost::math::constants::pi(); + const ecell4::Polygon poly = octahedron::make(); + + // check shape detection + BOOST_CHECK_EQUAL(poly.face_size(), 8u); + BOOST_CHECK_EQUAL(poly.edge_size(), 8u * 3u); + BOOST_CHECK_EQUAL(poly.vertex_size(), 6u); + BOOST_CHECK_CLOSE(poly.total_area(), 8 * std::sqrt(3.0) / 2, 1e-8); + + // check vertex position + BOOST_CHECK(static_cast(poly.find_vertex(octahedron::p1))); + BOOST_CHECK(static_cast(poly.find_vertex(octahedron::p2))); + BOOST_CHECK(static_cast(poly.find_vertex(octahedron::p3))); + BOOST_CHECK(static_cast(poly.find_vertex(octahedron::p4))); + BOOST_CHECK(static_cast(poly.find_vertex(octahedron::p5))); + BOOST_CHECK(static_cast(poly.find_vertex(octahedron::p6))); + + const VertexID v1 = *poly.find_vertex(octahedron::p1); + const VertexID v2 = *poly.find_vertex(octahedron::p2); + const VertexID v3 = *poly.find_vertex(octahedron::p3); + const VertexID v4 = *poly.find_vertex(octahedron::p4); + const VertexID v5 = *poly.find_vertex(octahedron::p5); + const VertexID v6 = *poly.find_vertex(octahedron::p6); + + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v1), octahedron::p1) - + octahedron::p1), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v2), octahedron::p2) - + octahedron::p2), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v3), octahedron::p3) - + octahedron::p3), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v4), octahedron::p4) - + octahedron::p4), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v5), octahedron::p5) - + octahedron::p5), 1e-8); + BOOST_CHECK_SMALL(ecell4::length( + poly.periodic_transpose(poly.position_at(v6), octahedron::p6) - + octahedron::p6), 1e-8); + + // check apex angle + BOOST_CHECK_CLOSE(poly.apex_angle_at(v1), 4.0 / 3.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v2), 4.0 / 3.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v3), 4.0 / 3.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v4), 4.0 / 3.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v5), 4.0 / 3.0 * pi, 1e-8); + BOOST_CHECK_CLOSE(poly.apex_angle_at(v6), 4.0 / 3.0 * pi, 1e-8); + + // check all the outgoing_edges are terminated at the correct vertex. + /* v1 */{ + const std::vector ans = + boost::assign::list_of(v2)(v3)(v4)(v5); + + std::vector result; result.reserve(4); + const std::vector es = poly.outgoing_edges(v1); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + /* v2 */{ + const std::vector ans = + boost::assign::list_of(v1)(v3)(v5)(v6); + + std::vector result; result.reserve(4); + const std::vector es = poly.outgoing_edges(v2); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + /* v3 */{ + const std::vector ans = + boost::assign::list_of(v1)(v2)(v4)(v6); + + std::vector result; result.reserve(4); + const std::vector es = poly.outgoing_edges(v3); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + /* v4 */{ + const std::vector ans = + boost::assign::list_of(v1)(v3)(v5)(v6); + + std::vector result; result.reserve(4); + const std::vector es = poly.outgoing_edges(v4); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + /* v5 */{ + const std::vector ans = + boost::assign::list_of(v1)(v2)(v4)(v6); + + std::vector result; result.reserve(4); + const std::vector es = poly.outgoing_edges(v5); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + /* v6 */{ + const std::vector ans = + boost::assign::list_of(v2)(v3)(v4)(v5); + + std::vector result; result.reserve(4); + const std::vector es = poly.outgoing_edges(v6); + for(typename std::vector::const_iterator + i(es.begin()), e(es.end()); i != e; ++i) + { + result.push_back(poly.target_of(*i)); + } + BOOST_CHECK(ans.size() == result.size()); + BOOST_CHECK(ecell::is_permutation( + ans.begin(), ans.end(), result.begin(), result.end())); + } + + // test of distance + const FaceID f1 = *(poly.find_face(v1, v2, v3)); + const FaceID f2 = *(poly.find_face(v1, v3, v4)); + const FaceID f3 = *(poly.find_face(v1, v4, v5)); + const FaceID f4 = *(poly.find_face(v1, v5, v2)); + const FaceID f5 = *(poly.find_face(v6, v2, v5)); + const FaceID f6 = *(poly.find_face(v6, v5, v4)); + const FaceID f7 = *(poly.find_face(v6, v4, v3)); + const FaceID f8 = *(poly.find_face(v6, v3, v2)); + { + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p1 + octahedron::p4 + octahedron::p5) / 3.0; + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f1), std::make_pair(p2, f3)), + std::sqrt(2.0), 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f3), std::make_pair(p1, f1)), + std::sqrt(2.0), 1e-8); + } + { + const Real3 p1 = (octahedron::p1 + octahedron::p3 + octahedron::p4) / 3.0; + const Real3 p2 = (octahedron::p1 + octahedron::p2 + octahedron::p5) / 3.0; + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f2), std::make_pair(p2, f4)), + std::sqrt(2.0), 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f4), std::make_pair(p1, f2)), + std::sqrt(2.0), 1e-8); + } + { + const Real3 p1 = (octahedron::p2 + octahedron::p6 + octahedron::p5) / 3.0; + const Real3 p2 = (octahedron::p3 + octahedron::p4 + octahedron::p6) / 3.0; + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f5), std::make_pair(p2, f7)), + std::sqrt(2.0), 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f7), std::make_pair(p1, f5)), + std::sqrt(2.0), 1e-8); + } + { + const Real3 p1 = (octahedron::p4 + octahedron::p5 + octahedron::p6) / 3.0; + const Real3 p2 = (octahedron::p2 + octahedron::p3 + octahedron::p6) / 3.0; + + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p1, f6), std::make_pair(p2, f8)), + std::sqrt(2.0), 1e-8); + BOOST_CHECK_CLOSE_FRACTION( + poly.distance(std::make_pair(p2, f8), std::make_pair(p1, f6)), + std::sqrt(2.0), 1e-8); + } + + { + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p4 + octahedron::p5 + octahedron::p6) / 3.0; + + BOOST_CHECK_EQUAL( + poly.distance(std::make_pair(p1, f1), std::make_pair(p2, f6)), + std::numeric_limits::infinity()); + BOOST_CHECK_EQUAL( + poly.distance(std::make_pair(p2, f6), std::make_pair(p1, f1)), + std::numeric_limits::infinity()); + } + + // distance between vtx and (face|vertex) + + { + const Real d12 = ::ecell4::polygon::distance(poly, + std::make_pair(octahedron::p1, v1), + std::make_pair(octahedron::p2, v2)); + const Real dsq12 = ::ecell4::polygon::distance_sq(poly, + std::make_pair(octahedron::p1, v1), + std::make_pair(octahedron::p2, v2)); + + const Real ex_d12 = ::ecell4::length(octahedron::p1 - octahedron::p2); + const Real ex_dsq12 = ::ecell4::length_sq(octahedron::p1 - octahedron::p2); + + BOOST_CHECK_CLOSE_FRACTION(d12, ex_d12, 1e-8); + BOOST_CHECK_CLOSE_FRACTION(dsq12, ex_dsq12, 1e-8); + } + + { + const Real d16 = ::ecell4::polygon::distance(poly, + std::make_pair(octahedron::p1, v1), + std::make_pair(octahedron::p6, v6)); + const Real dsq16 = ::ecell4::polygon::distance_sq(poly, + std::make_pair(octahedron::p1, v1), + std::make_pair(octahedron::p6, v6)); + + const Real ex_d16 = std::sqrt(6.0); + const Real ex_dsq16 = 6.0; + + BOOST_CHECK_CLOSE_FRACTION(d16, ex_d16, 1e-8); + BOOST_CHECK_CLOSE_FRACTION(dsq16, ex_dsq16, 1e-8); + } + + { + const Real3 p456 = (octahedron::p4 + octahedron::p5 + octahedron::p6) / 3.0; + + const Real d1 = ::ecell4::polygon::distance(poly, + std::make_pair(octahedron::p1, v1), std::make_pair(p456, f6)); + const Real d2 = ::ecell4::polygon::distance(poly, + std::make_pair(p456, f6), std::make_pair(octahedron::p1, v1)); + BOOST_CHECK_EQUAL(d1, d2); + + const Real dsq1 = ::ecell4::polygon::distance_sq(poly, + std::make_pair(octahedron::p1, v1), std::make_pair(p456, f6)); + const Real dsq2 = ::ecell4::polygon::distance_sq(poly, + std::make_pair(p456, f6), std::make_pair(octahedron::p1, v1)); + BOOST_CHECK_EQUAL(dsq1, dsq2); + + const Real ex_d1 = 2.0 * std::sqrt(2.0 / 3.0); + const Real ex_dsq1 = 8.0 / 3.0; + + BOOST_CHECK_CLOSE_FRACTION(d1, ex_d1, 1e-8); + BOOST_CHECK_CLOSE_FRACTION(dsq1, ex_dsq1, 1e-8); + } + + // travel + { + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p2 * 2 + octahedron::p3 * 2 - octahedron::p1) / 3.0; + + const std::pair p2_ = + poly.travel(std::make_pair(p1, f1), p2 - p1); + + BOOST_CHECK_EQUAL(p2_.second, f8); + + const Real3 dst = (octahedron::p2 + octahedron::p3 + octahedron::p6) / 3.0; + BOOST_CHECK_CLOSE(p2_.first[0], dst[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], dst[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], dst[2], 1e-6); + + const Real dist = poly.distance(std::make_pair(p1, f1), p2_); + BOOST_CHECK_CLOSE(dist, length(p2 - p1), 1e-6); + } + { + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p1 * 2 + octahedron::p2 * 2 - octahedron::p3) / 3.0; + + const std::pair p2_ = + poly.travel(std::make_pair(p1, f1), p2 - p1); + + BOOST_CHECK_EQUAL(p2_.second, f4); + + const Real3 dst = (octahedron::p1 + octahedron::p2 + octahedron::p5) / 3.0; + BOOST_CHECK_CLOSE(p2_.first[0], dst[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], dst[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], dst[2], 1e-6); + + const Real dist = poly.distance(std::make_pair(p1, f1), p2_); + BOOST_CHECK_CLOSE(dist, length(p2 - p1), 1e-6); + } + { + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p1 * 2 + octahedron::p3 * 2 - octahedron::p2) / 3.0; + + const std::pair p2_ = + poly.travel(std::make_pair(p1, f1), p2 - p1); + + BOOST_CHECK_EQUAL(p2_.second, f2); + + const Real3 dst = (octahedron::p1 + octahedron::p3 + octahedron::p4) / 3.0; + BOOST_CHECK_CLOSE(p2_.first[0], dst[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], dst[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], dst[2], 1e-6); + + const Real dist = poly.distance(std::make_pair(p1, f1), p2_); + BOOST_CHECK_CLOSE(dist, length(p2 - p1), 1e-6); + } + + // roll + { + const VertexID vid = v1; + const Real r = std::sqrt(2.0 / 3.0); + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p1 + octahedron::p3 + octahedron::p4) / 3.0; + const Real3 p3 = (octahedron::p1 + octahedron::p4 + octahedron::p5) / 3.0; + const Real3 p4 = (octahedron::p1 + octahedron::p2 + octahedron::p5) / 3.0; + + { + const std::pair no_move = + ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v1, r, 0.0); + BOOST_CHECK_EQUAL(no_move.second, f1); + BOOST_CHECK_CLOSE(no_move.first[0], p1[0], 1e-6); + BOOST_CHECK_CLOSE(no_move.first[1], p1[1], 1e-6); + BOOST_CHECK_CLOSE(no_move.first[2], p1[2], 1e-6); + } + const std::pair p2_ = ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v1, r, 60.0 / 180.0 * pi); + const std::pair p3_ = ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v1, r, 120.0 / 180.0 * pi); + const std::pair p4_ = ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v1, r, 180.0 / 180.0 * pi); + const std::pair p1_ = ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v1, r, 240.0 / 180.0 * pi); + BOOST_CHECK_EQUAL(p2_.second, f2); + BOOST_CHECK_EQUAL(p3_.second, f3); + BOOST_CHECK_EQUAL(p4_.second, f4); + BOOST_CHECK_EQUAL(p1_.second, f1); + + BOOST_CHECK_CLOSE(p1_.first[0], p1[0], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[1], p1[1], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[2], p1[2], 1e-6); + + BOOST_CHECK_CLOSE(p2_.first[0], p2[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], p2[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], p2[2], 1e-6); + + BOOST_CHECK_CLOSE(p3_.first[0], p3[0], 1e-6); + BOOST_CHECK_CLOSE(p3_.first[1], p3[1], 1e-6); + BOOST_CHECK_CLOSE(p3_.first[2], p3[2], 1e-6); + + BOOST_CHECK_CLOSE(p4_.first[0], p4[0], 1e-6); + BOOST_CHECK_CLOSE(p4_.first[1], p4[1], 1e-6); + BOOST_CHECK_CLOSE(p4_.first[2], p4[2], 1e-6); + } + + { + const VertexID vid = v1; + const Real r = std::sqrt(2.0 / 3.0); + const Real3 p1 = (octahedron::p1 + octahedron::p2 + octahedron::p3) / 3.0; + const Real3 p2 = (octahedron::p1 + octahedron::p3 + octahedron::p4) / 3.0; + const Real3 p3 = (octahedron::p1 + octahedron::p4 + octahedron::p5) / 3.0; + const Real3 p4 = (octahedron::p1 + octahedron::p2 + octahedron::p5) / 3.0; + + { + const std::pair no_move = + ::ecell4::polygon::roll(poly, std::make_pair(p3, f3), v1, r, 0.0); + BOOST_CHECK_EQUAL(no_move.second, f3); + BOOST_CHECK_CLOSE(no_move.first[0], p3[0], 1e-6); + BOOST_CHECK_CLOSE(no_move.first[1], p3[1], 1e-6); + BOOST_CHECK_CLOSE(no_move.first[2], p3[2], 1e-6); + } + const std::pair p4_ = ::ecell4::polygon::roll(poly, std::make_pair(p3, f3), v1, r, 60.0 / 180.0 * pi); + const std::pair p1_ = ::ecell4::polygon::roll(poly, std::make_pair(p3, f3), v1, r, 120.0 / 180.0 * pi); + const std::pair p2_ = ::ecell4::polygon::roll(poly, std::make_pair(p3, f3), v1, r, 180.0 / 180.0 * pi); + const std::pair p3_ = ::ecell4::polygon::roll(poly, std::make_pair(p3, f3), v1, r, 240.0 / 180.0 * pi); + BOOST_CHECK_EQUAL(p2_.second, f2); + BOOST_CHECK_EQUAL(p3_.second, f3); + BOOST_CHECK_EQUAL(p4_.second, f4); + BOOST_CHECK_EQUAL(p1_.second, f1); + + BOOST_CHECK_CLOSE(p1_.first[0], p1[0], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[1], p1[1], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[2], p1[2], 1e-6); + + BOOST_CHECK_CLOSE(p2_.first[0], p2[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], p2[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], p2[2], 1e-6); + + BOOST_CHECK_CLOSE(p3_.first[0], p3[0], 1e-6); + BOOST_CHECK_CLOSE(p3_.first[1], p3[1], 1e-6); + BOOST_CHECK_CLOSE(p3_.first[2], p3[2], 1e-6); + + BOOST_CHECK_CLOSE(p4_.first[0], p4[0], 1e-6); + BOOST_CHECK_CLOSE(p4_.first[1], p4[1], 1e-6); + BOOST_CHECK_CLOSE(p4_.first[2], p4[2], 1e-6); + } + + { + std::shared_ptr rng = std::make_shared(12345); + for(std::size_t i=0; i<1000; ++i) + { + FaceID f1, f2; + const Real3 p1 = poly.draw_position(rng, f1); + const Real3 p2 = poly.draw_position(rng, f2); + + const Real d_3d = length(poly.periodic_transpose(p1, p2) - p2); + const Real d_2d = ::ecell4::polygon::distance(poly, std::make_pair(p1, f1), std::make_pair(p2, f2)); + BOOST_CHECK(d_2d >= d_3d); + } + } + +} + +//! test data 3: plane +// below, the normal vector towords the depth of your display. +// +// each edge has length 2. +// +--> x +// | 0 __1__2__3__4__ 0 +// | |\ |\ |\ |\ |\ | +// v 5|_\|_\|_\|_\9_\|5 +// y |\ |\ |\ |\ |\ | +// .|_\|_\|_\|_\|_\| . +// .|\ |\ |\ |\ |\ | . +// .|_\|_\|_\|_\|_\| . +// |\ |\ |\ |\ |\ | +// 20|_\|_\|_\|_\24\|20 +// |\ |\ |\ |\ |\ | +// 0|_\|_\|_\|_\|_\|0 +// +struct plane +{ + const static Real3 edge_length; + + static ecell4::Polygon make() + { + std::vector triangles; + for(std::size_t j=0; j<5; ++j) + { + const Real y_up = 2.0 * (j+1); + const Real y_lw = 2.0 * j; + for(std::size_t i=0; i<5; ++i) + { + const Real x_up = 2.0 * (i+1); + const Real x_lw = 2.0 * i; + + const Real3 uxuy = Real3(x_up, y_up, 5.0); + const Real3 uxly = Real3(x_up, y_lw, 5.0); + const Real3 lxuy = Real3(x_lw, y_up, 5.0); + const Real3 lxly = Real3(x_lw, y_lw, 5.0); + + triangles.push_back(Triangle(lxly, uxly, uxuy)); + triangles.push_back(Triangle(uxuy, lxuy, lxly)); + } + } + return ecell4::Polygon(edge_length, triangles); + } +}; +const Real3 plane::edge_length = Real3(10, 10, 10); + +BOOST_AUTO_TEST_CASE(Polygon_plane_construction_from_triangles) +{ + const Real pi = boost::math::constants::pi(); + const ecell4::Polygon poly = plane::make(); + + // check shape detection + BOOST_CHECK_EQUAL(poly.face_size(), 50u); + BOOST_CHECK_EQUAL(poly.edge_size(), 50u * 3u); + BOOST_CHECK_EQUAL(poly.vertex_size(), 25u); + BOOST_CHECK_CLOSE(poly.total_area(), 10 * 10, 1e-8); + + // check vertex positions + for(std::size_t j=0; j<5; ++j) + { + const Real y = 2.0 * j; + for(std::size_t i=0; i<5; ++i) + { + const Real x = 2.0 * i; + BOOST_CHECK(static_cast(poly.find_vertex(Real3(x, y, 5.0)))); + } + } + + // check all the vertices has 6 outgoing-edges under the PBC + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + BOOST_CHECK_EQUAL(poly.outgoing_edges(*i).size(), 6u); + } + } + + // check normal vector + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + BOOST_CHECK_SMALL(poly.triangle_at(*i).normal()[0], 1e-8); + BOOST_CHECK_SMALL(poly.triangle_at(*i).normal()[1], 1e-8); + BOOST_CHECK_CLOSE(poly.triangle_at(*i).normal()[2], 1.0, 1e-8); + } + } + // check areas + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + BOOST_CHECK_CLOSE(poly.triangle_at(*i).area(), 2.0, 1e-8); + } + } + // check angles + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + const Triangle& t = poly.triangle_at(*i); + for(std::size_t idx=0; idx<3; ++idx) + { + const Real d45 = std::abs(t.angle_at(idx) - pi / 4.0); + const Real d90 = std::abs(t.angle_at(idx) - pi / 2.0); + BOOST_CHECK(d45 < 1e-8 || d90 < 1e-8); + } + } + } + + + // check opposite edges + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + const VertexID vid = *i; + std::vector const& outs = poly.outgoing_edges(vid); + for(std::vector::const_iterator + oi(outs.begin()), oe(outs.end()); oi != oe; ++oi) + { + BOOST_CHECK_EQUAL(poly.target_of(poly.opposite_of(*oi)), vid); + } + } + } + + // check next edges + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + const VertexID vid = *i; + std::vector const& outs = poly.outgoing_edges(vid); + for(std::vector::const_iterator + oi(outs.begin()), oe(outs.end()); oi != oe; ++oi) + { + BOOST_CHECK_EQUAL( + poly.target_of(poly.next_of(poly.next_of(*oi))), vid); + } + } + } + + // check apex angle; everywhere is flat + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + BOOST_CHECK_CLOSE(poly.apex_angle_at(*i), 2.0 * pi, 1e-8); + } + } + + // check tilt angle + { + const std::vector eids = poly.list_edge_ids(); + assert(eids.size() == poly.edge_size()); + + for(std::vector::const_iterator + i(eids.begin()), e(eids.end()); i!=e; ++i) + { + BOOST_CHECK_SMALL(poly.tilt_angle_at(*i), 1e-8); + } + } + + // check neighbor list + // + // The shaded triangle have 12 neighbors (excluding self) + // ___ ___ ___ + // | /| /| /| + // | /7|6/5|4/3| + // |/__|/__|/__| + // | /|##/| /| + // |8/9|#/1|2/ | + // |/__|/__|/__| + // |10/|12/| /| + // | / | / | / | + // |/11|/__|/__| + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + BOOST_CHECK_EQUAL(poly.neighbor_faces_of(*i).size(), 12); + } + + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + BOOST_CHECK_EQUAL(poly.neighbor_faces_of(*i).size(), 12); + } + } + + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + std::vector vneighbors; + for(std::size_t idx=0; idx<3; ++idx) + { + const std::vector es = poly.outgoing_edges( + poly.vertices_of(*i).at(idx)); + for(std::vector::const_iterator + ie(es.begin()), ee(es.end()); ie!=ee; ++ie) + { + vneighbors.push_back(poly.face_of(*ie)); + } + } + std::sort(vneighbors.begin(), vneighbors.end()); + const std::vector::iterator uniq = + std::unique(vneighbors.begin(), vneighbors.end()); + vneighbors.erase(uniq, vneighbors.end()); + const std::vector::iterator self = + std::find(vneighbors.begin(), vneighbors.end(), *i); + vneighbors.erase(self); + + const std::vector fneighbors = poly.neighbor_faces_of(*i); + BOOST_CHECK(ecell::is_permutation( + fneighbors.begin(), fneighbors.end(), + vneighbors.begin(), vneighbors.end())); + } + + } + + // distance stuff + // + // 24___20____21 + // |\ |\ | + // | \12| \14| + // |11\ |13\ | + // 4|___\0___\1____2 + // |\ |\ |\ | + // | \6 | \2 | \4 | + // | 5\ | 1\ | 3\ | + // 9|___\5___\6___\7 + // |\ |\ | + // | \8 | \10| + // | 7\ | 9\ | + // 10|___\11__\|12 + + const VertexID v0 = *poly.find_vertex(Real3(0.0, 0.0, 5.0)); + const VertexID v1 = *poly.find_vertex(Real3(2.0, 0.0, 5.0)); + const VertexID v2 = *poly.find_vertex(Real3(4.0, 0.0, 5.0)); + const VertexID v4 = *poly.find_vertex(Real3(8.0, 0.0, 5.0)); + + const VertexID v5 = *poly.find_vertex(Real3(0.0, 2.0, 5.0)); + const VertexID v6 = *poly.find_vertex(Real3(2.0, 2.0, 5.0)); + const VertexID v7 = *poly.find_vertex(Real3(4.0, 2.0, 5.0)); + const VertexID v9 = *poly.find_vertex(Real3(8.0, 2.0, 5.0)); + + const VertexID v10 = *poly.find_vertex(Real3(0.0, 4.0, 5.0)); + const VertexID v11 = *poly.find_vertex(Real3(2.0, 4.0, 5.0)); + const VertexID v12 = *poly.find_vertex(Real3(4.0, 4.0, 5.0)); + + const VertexID v20 = *poly.find_vertex(Real3(0.0, 8.0, 5.0)); + const VertexID v21 = *poly.find_vertex(Real3(2.0, 8.0, 5.0)); + const VertexID v24 = *poly.find_vertex(Real3(8.0, 8.0, 5.0)); + + const FaceID f1 = *poly.find_face(v0, v5, v6); + const FaceID f2 = *poly.find_face(v0, v1, v6); + + const FaceID f3 = *poly.find_face(v1, v6, v7); + const FaceID f4 = *poly.find_face(v1, v2, v7); + + const FaceID f5 = *poly.find_face(v4, v5, v9); + const FaceID f6 = *poly.find_face(v0, v4, v5); + + const FaceID f7 = *poly.find_face(v5, v10, v11); + const FaceID f8 = *poly.find_face(v5, v6, v11); + + const FaceID f9 = *poly.find_face(v6, v11, v12); + const FaceID f10 = *poly.find_face(v6, v7, v12); + + const FaceID f11 = *poly.find_face(v0, v4, v24); + const FaceID f12 = *poly.find_face(v0, v20, v24); + + const FaceID f13 = *poly.find_face(v0, v1, v20); + const FaceID f14 = *poly.find_face(v1, v20, v21); + + { + const EdgeID e0_01 = *poly.find_edge(v0, v1); + const EdgeID e0_20 = *poly.find_edge(v0, v20); + const EdgeID e0_24 = *poly.find_edge(v0, v24); + const EdgeID e0_04 = *poly.find_edge(v0, v4); + const EdgeID e0_05 = *poly.find_edge(v0, v5); + const EdgeID e0_06 = *poly.find_edge(v0, v6); + BOOST_CHECK_EQUAL(poly.opposite_of(poly.next_of(poly.next_of(e0_01))), e0_06); + BOOST_CHECK_EQUAL(poly.opposite_of(poly.next_of(poly.next_of(e0_06))), e0_05); + BOOST_CHECK_EQUAL(poly.opposite_of(poly.next_of(poly.next_of(e0_05))), e0_04); + BOOST_CHECK_EQUAL(poly.opposite_of(poly.next_of(poly.next_of(e0_04))), e0_24); + BOOST_CHECK_EQUAL(poly.opposite_of(poly.next_of(poly.next_of(e0_24))), e0_20); + BOOST_CHECK_EQUAL(poly.opposite_of(poly.next_of(poly.next_of(e0_20))), e0_01); + } + + { + const Real3 p1(0.5, 1.5, 5.0); + const Real3 p2(1.5, 0.5, 5.0); + BOOST_CHECK_CLOSE_FRACTION(poly.distance( + std::make_pair(p1, f1), std::make_pair(p2, f2)), + length(poly.periodic_transpose(p1, p2) - p2), 1e-8); + BOOST_CHECK_CLOSE_FRACTION(poly.distance( + std::make_pair(p2, f2), std::make_pair(p1, f1)), + length(poly.periodic_transpose(p1, p2) - p2), 1e-8); + } + + { + const Real3 p1(0.5, 1.5, 5.0); + const Real3 p2(8.5, 9.5, 5.0); + BOOST_CHECK_CLOSE_FRACTION(poly.distance( + std::make_pair(p1, f1), std::make_pair(p2, f11)), + length(poly.periodic_transpose(p1, p2) - p2), 1e-8); + BOOST_CHECK_CLOSE_FRACTION(poly.distance( + std::make_pair(p2, f11), std::make_pair(p1, f1)), + length(poly.periodic_transpose(p1, p2) - p2), 1e-8); + } + + { + const Real3 p1(0.5, 1.5, 5.0); + const Real3 p2(1.5, 0.5, 5.0); + + const Real3 v1to2 = poly.direction( + std::make_pair(p1, f1), std::make_pair(p2, f2)); + const Real3 v2to1 = poly.direction( + std::make_pair(p2, f2), std::make_pair(p1, f1)); + BOOST_CHECK_CLOSE(v1to2[0], 1.0, 1e-6); + BOOST_CHECK_CLOSE(v1to2[1], -1.0, 1e-6); + BOOST_CHECK_SMALL(v1to2[2], 1e-6); + + BOOST_CHECK_CLOSE(v2to1[0], -1.0, 1e-6); + BOOST_CHECK_CLOSE(v2to1[1], 1.0, 1e-6); + BOOST_CHECK_SMALL(v2to1[2], 1e-6); + } + + { + const Real3 p1(0.5, 1.5, 5.0); + const Real3 p2(8.5, 9.5, 5.0); + const Real3 v1to2 = poly.direction( + std::make_pair(p1, f1), std::make_pair(p2, f11)); + const Real3 v2to1 = poly.direction( + std::make_pair(p2, f11), std::make_pair(p1, f1)); + + BOOST_CHECK_CLOSE(v1to2[0], -2.0, 1e-6); + BOOST_CHECK_CLOSE(v1to2[1], -2.0, 1e-6); + BOOST_CHECK_SMALL(v1to2[2], 1e-6); + + BOOST_CHECK_CLOSE(v2to1[0], 2.0, 1e-6); + BOOST_CHECK_CLOSE(v2to1[1], 2.0, 1e-6); + BOOST_CHECK_SMALL(v2to1[2], 1e-6); + } + + // traveling ---------------------------------------------------------- + + { + const Real3 p1(0.5, 1.5, 5.0); + const Real3 p2(1.5, 0.5, 5.0); + + const std::pair p2_ = + poly.travel(std::make_pair(p1, f1), Real3(1.0, -1.0, 0.0)); + const std::pair p1_ = + poly.travel(std::make_pair(p2, f2), Real3(-1.0, 1.0, 0.0)); + + BOOST_CHECK_EQUAL(p1_.second, f1); + BOOST_CHECK_EQUAL(p2_.second, f2); + + BOOST_CHECK_CLOSE(p1_.first[0], p1[0], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[1], p1[1], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[2], p1[2], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[0], p2[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], p2[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], p2[2], 1e-6); + + } + + { + const Real3 p1(0.5, 1.5, 5.0); + const Real3 p2(8.5, 9.5, 5.0); + + const std::pair p2_ = + poly.travel(std::make_pair(p1, f1), Real3(-2.0, -2.0, 0.0)); + const std::pair p1_ = + poly.travel(std::make_pair(p2, f11), Real3( 2.0, 2.0, 0.0)); + + BOOST_CHECK_EQUAL(p1_.second, f1); + BOOST_CHECK_EQUAL(p2_.second, f11); + + BOOST_CHECK_CLOSE(p1_.first[0], p1[0], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[1], p1[1], 1e-6); + BOOST_CHECK_CLOSE(p1_.first[2], p1[2], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[0], p2[0], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[1], p2[1], 1e-6); + BOOST_CHECK_CLOSE(p2_.first[2], p2[2], 1e-6); + } + + // roll ---------------------------------------------------------- + + { + // around v6, far from Boundary + const Real3 p1(2.0 - std::sqrt(3.0), 1.0, 5.0); + const std::pair p2 = + ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v6, 2, 30.0 / 180.0 * pi); + + BOOST_CHECK_EQUAL(p2.second, f2); + BOOST_CHECK_CLOSE(p2.first[0], 1.0, 1e-6); + BOOST_CHECK_CLOSE(p2.first[1], 2.0 - std::sqrt(3.0), 1e-6); + BOOST_CHECK_CLOSE(p2.first[2], 5.0, 1e-6); + + const std::pair p10 = + ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v6, 2, pi); + BOOST_CHECK_EQUAL(p10.second, f10); + BOOST_CHECK_CLOSE(p10.first[0], 2.0 + std::sqrt(3.0), 1e-6); + BOOST_CHECK_CLOSE(p10.first[1], 3.0, 1e-6); + BOOST_CHECK_CLOSE(p10.first[2], 5.0, 1e-6); + } + { + const Real3 p1(1.0, std::sqrt(3.0), 5.0); + const Real3 p2(std::sqrt(3.0), 1.0, 5.0); + + const std::pair p11 = + ::ecell4::polygon::roll(poly, std::make_pair(p2, f2), v0, 2, pi); + BOOST_CHECK_EQUAL(p11.second, f11); + BOOST_CHECK_CLOSE(p11.first[0], 10.0 - std::sqrt(3.0), 1e-6); + BOOST_CHECK_CLOSE(p11.first[1], 9.0, 1e-6); + BOOST_CHECK_CLOSE(p11.first[2], 5.0, 1e-6); + + const std::pair p12 = + ::ecell4::polygon::roll(poly, std::make_pair(p1, f1), v0, 2, pi); + BOOST_CHECK_EQUAL(p12.second, f12); + BOOST_CHECK_CLOSE(p12.first[0], 9.0, 1e-6); + BOOST_CHECK_CLOSE(p12.first[1], 10.0 - std::sqrt(3.0), 1e-6); + BOOST_CHECK_CLOSE(p12.first[2], 5.0, 1e-6); + } + + // -------------------------------------------------------------------------- + // distance + + { + std::shared_ptr rng = std::make_shared(12345); + for(std::size_t i=0; i<1000; ++i) + { + FaceID f1, f2; + const Real3 p1 = poly.draw_position(rng, f1); + const Real3 p2 = poly.draw_position(rng, f2); + + const Real d_3d = length(poly.periodic_transpose(p1, p2) - p2); + const Real d_2d = ::ecell4::polygon::distance(poly, std::make_pair(p1, f1), std::make_pair(p2, f2)); + BOOST_CHECK(d_2d * (1 + 1e-8) /* = relative tolerance*/ >= d_3d); + if(d_2d < d_3d) + { + BOOST_TEST_MESSAGE(""d_2d("" << d_2d << "") < d_3d("" << d_3d << "")""); + } + } + } +} + +//! test data 4: deformed plane +// below, the normal vector towords the depth of your display. +// +// The plane has a peak at the center. +// +// each edge has length 2. +// +--> x +// | 0 __1__2__3__4__ 0 +// | |\ |\ |\ |\ |\ | +// v 5|_\|_\|_\|_\9_\|5 +// y |\ |\ |\ |\ |\ | +// .|_\|_\|_\|_\|_\| . +// .|\ |\ |\ |\ |\ | . +// .|_\|_\|_\|_\|_\| . +// |\ |\ |\ |\ |\ | +// 20|_\|_\|_\|_\24\|20 +// |\ |\ |\ |\ |\ | +// 0|_\|_\|_\|_\|_\|0 +// +struct gaussian_hill +{ + const static Real3 edge_length; + + static Real gaussian(const Real x, const Real y) + { + return 2.0 * std::exp(-0.5 * ((x-5.0) * (x-5.0) + (y-5.0) * (y-5.0))); + } + + static ecell4::Polygon make() + { + std::vector triangles; + for(std::size_t j=0; j<5; ++j) + { + const Real y_up = 2.0 * (j+1); + const Real y_lw = 2.0 * j; + for(std::size_t i=0; i<5; ++i) + { + const Real x_up = 2.0 * (i+1); + const Real x_lw = 2.0 * i; + + const Real3 uxuy = Real3(x_up, y_up, gaussian(x_up, y_up)); + const Real3 uxly = Real3(x_up, y_lw, gaussian(x_up, y_lw)); + const Real3 lxuy = Real3(x_lw, y_up, gaussian(x_lw, y_up)); + const Real3 lxly = Real3(x_lw, y_lw, gaussian(x_lw, y_lw)); + + triangles.push_back(Triangle(lxly, uxly, uxuy)); + triangles.push_back(Triangle(uxuy, lxuy, lxly)); + } + } + return ecell4::Polygon(edge_length, triangles); + } +}; +const Real3 gaussian_hill::edge_length = Real3(10, 10, 10); + +BOOST_AUTO_TEST_CASE(Polygon_hill_construction_from_triangles) +{ + const Real pi = boost::math::constants::pi(); + const ecell4::Polygon poly = gaussian_hill::make(); + + // check shape detection + BOOST_CHECK_EQUAL(poly.face_size(), 50u); + BOOST_CHECK_EQUAL(poly.edge_size(), 50u * 3u); + BOOST_CHECK_EQUAL(poly.vertex_size(), 25u); + // the total area of the hill is non-trivial. + // BOOST_CHECK_CLOSE(poly.total_area(), 10 * 10, 1e-8); + + // check vertex positions + for(std::size_t j=0; j<5; ++j) + { + const Real y = 2.0 * j; + for(std::size_t i=0; i<5; ++i) + { + const Real x = 2.0 * i; + const Real3 position(x, y, gaussian_hill::gaussian(x, y)); + BOOST_CHECK(static_cast(poly.find_vertex(position))); + } + } + + // check all the vertices has 6 outgoing-edges under the PBC + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + BOOST_CHECK_EQUAL(poly.outgoing_edges(*i).size(), 6u); + } + } + +// // check normal vector +// { +// const std::vector fids = poly.list_face_ids(); +// assert(fids.size() == poly.face_size()); +// +// for(std::vector::const_iterator +// i(fids.begin()), e(fids.end()); i!=e; ++i) +// { +// BOOST_CHECK_SMALL(poly.triangle_at(*i).normal()[0], 1e-8); +// BOOST_CHECK_SMALL(poly.triangle_at(*i).normal()[1], 1e-8); +// BOOST_CHECK_CLOSE(poly.triangle_at(*i).normal()[2], 1.0, 1e-8); +// } +// } +// // check areas +// { +// const std::vector fids = poly.list_face_ids(); +// assert(fids.size() == poly.face_size()); +// +// for(std::vector::const_iterator +// i(fids.begin()), e(fids.end()); i!=e; ++i) +// { +// BOOST_CHECK_CLOSE(poly.triangle_at(*i).area(), 2.0, 1e-8); +// } +// } +// // check angles +// { +// const std::vector fids = poly.list_face_ids(); +// assert(fids.size() == poly.face_size()); +// +// for(std::vector::const_iterator +// i(fids.begin()), e(fids.end()); i!=e; ++i) +// { +// const Triangle& t = poly.triangle_at(*i); +// for(std::size_t idx=0; idx<3; ++idx) +// { +// const Real d45 = std::abs(t.angle_at(idx) - pi / 4.0); +// const Real d90 = std::abs(t.angle_at(idx) - pi / 2.0); +// BOOST_CHECK(d45 < 1e-8 || d90 < 1e-8); +// } +// } +// } + + // check opposite edges + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + const VertexID vid = *i; + std::vector const& outs = poly.outgoing_edges(vid); + for(std::vector::const_iterator + oi(outs.begin()), oe(outs.end()); oi != oe; ++oi) + { + BOOST_CHECK_EQUAL(poly.target_of(poly.opposite_of(*oi)), vid); + } + } + } + + // check next edges + { + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + const VertexID vid = *i; + std::vector const& outs = poly.outgoing_edges(vid); + for(std::vector::const_iterator + oi(outs.begin()), oe(outs.end()); oi != oe; ++oi) + { + BOOST_CHECK_EQUAL( + poly.target_of(poly.next_of(poly.next_of(*oi))), vid); + } + } + } + + // apex angles are also non-trivial. +// { +// const std::vector vids = poly.list_vertex_ids(); +// assert(vids.size() == poly.vertex_size()); +// +// for(std::vector::const_iterator +// i(vids.begin()), e(vids.end()); i!=e; ++i) +// { +// BOOST_REQUIRE_MESSAGE(poly.apex_angle_at(*i) <= 2.0 * pi + 1e-8, +// ""apex angle = "" << poly.apex_angle_at(*i)); +// } +// } + +// // check tilt angle +// { +// const std::vector eids = poly.list_edge_ids(); +// assert(eids.size() == poly.edge_size()); +// +// for(std::vector::const_iterator +// i(eids.begin()), e(eids.end()); i!=e; ++i) +// { +// BOOST_CHECK_SMALL(poly.tilt_angle_at(*i), 1e-8); +// } +// } + + // check neighbor list + // + // The shaded triangle have 12 neighbors (excluding self) + // ___ ___ ___ + // | /| /| /| + // | /7|6/5|4/3| + // |/__|/__|/__| + // | /|##/| /| + // |8/9|#/1|2/ | + // |/__|/__|/__| + // |10/|12/| /| + // | / | / | / | + // |/11|/__|/__| + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + BOOST_CHECK_EQUAL(poly.neighbor_faces_of(*i).size(), 12); + } + + const std::vector vids = poly.list_vertex_ids(); + assert(vids.size() == poly.vertex_size()); + + for(std::vector::const_iterator + i(vids.begin()), e(vids.end()); i!=e; ++i) + { + BOOST_CHECK_EQUAL(poly.neighbor_faces_of(*i).size(), 12); + } + } + + { + const std::vector fids = poly.list_face_ids(); + assert(fids.size() == poly.face_size()); + + for(std::vector::const_iterator + i(fids.begin()), e(fids.end()); i!=e; ++i) + { + std::vector vneighbors; + for(std::size_t idx=0; idx<3; ++idx) + { + const std::vector es = poly.outgoing_edges( + poly.vertices_of(*i).at(idx)); + for(std::vector::const_iterator + ie(es.begin()), ee(es.end()); ie!=ee; ++ie) + { + vneighbors.push_back(poly.face_of(*ie)); + } + } + std::sort(vneighbors.begin(), vneighbors.end()); + const std::vector::iterator uniq = + std::unique(vneighbors.begin(), vneighbors.end()); + vneighbors.erase(uniq, vneighbors.end()); + const std::vector::iterator self = + std::find(vneighbors.begin(), vneighbors.end(), *i); + vneighbors.erase(self); + + const std::vector fneighbors = poly.neighbor_faces_of(*i); + BOOST_CHECK(ecell::is_permutation( + fneighbors.begin(), fneighbors.end(), + vneighbors.begin(), vneighbors.end())); + } + + } + + // -------------------------------------------------------------------------- + // distance + + { + std::shared_ptr rng = std::make_shared(12345); + for(std::size_t i=0; i<1000; ++i) + { + FaceID f1, f2; + const Real3 p1 = poly.draw_position(rng, f1); + const Real3 p2 = poly.draw_position(rng, f2); + + const Real d_3d = length(poly.periodic_transpose(p1, p2) - p2); + const Real d_2d = ::ecell4::polygon::distance(poly, std::make_pair(p1, f1), std::make_pair(p2, f2)); + BOOST_CHECK(d_2d * (1 + 1e-8) /* = relative tolerance*/ >= d_3d); + if(d_2d < d_3d) + { + BOOST_TEST_MESSAGE(""d_2d("" << d_2d << "") < d_3d("" << d_3d << "")""); + } + } + } +} + +// ============================================================================ +// +// | |\ Z +// | |_\ p4 (5,2,28) +// +--+-----------+--------------+ |\`. +// | * | | | \ `. +// | | | | \ `. +// | |\ | |\ | p1 | \ `. p3 (6,3,25) +// | |_\ *--+>|_\ * | (5,2,25) `-. \ .` Y +// +--------------+--------------+ `-.\.' +// 0 20 p2 (6,2,25) X +// + +BOOST_AUTO_TEST_CASE(Polygon_list_faces_within_radius) +{ + const Real3 edges(10.0, 20.0, 30.0); + + const Real3 p1(5.0, 2.0, 25.0); + const Real3 p2(6.0, 2.0, 25.0); + const Real3 p3(5.0, 3.0, 25.0); + const Real3 p4(5.0, 2.0, 28.0); + + std::vector triangles; + triangles.push_back(Triangle(p1, p2, p4)); // f1 + triangles.push_back(Triangle(p1, p4, p3)); // f2 + triangles.push_back(Triangle(p1, p3, p2)); // f3 + triangles.push_back(Triangle(p2, p3, p4)); // f4 + + ecell4::Polygon poly(edges, triangles); + + const VertexID v1 = *poly.find_vertex(p1); + const VertexID v2 = *poly.find_vertex(p2); + const VertexID v3 = *poly.find_vertex(p3); + const VertexID v4 = *poly.find_vertex(p4); + + const FaceID f1 = *(poly.find_face(v1, v2, v3)); + const FaceID f2 = *(poly.find_face(v1, v2, v4)); + const FaceID f3 = *(poly.find_face(v1, v3, v4)); + const FaceID f4 = *(poly.find_face(v2, v3, v4)); + + const auto check_x = poly.list_faces_within_radius(Real3(4.0, 2.0, 25.0), 1.1); + bool find_x = false; + for(const auto& found_x : check_x) + { + if(found_x.first.first == f2) {find_x = true;} + } + BOOST_CHECK(find_x); + + const auto check_y = poly.list_faces_within_radius(Real3(5.0, 19.0, 25.0), 3.1); + bool find_y = false; + for(const auto& found_y : check_y) + { + if(found_y.first.first == f1) {find_y = true;} + } + BOOST_CHECK(find_y); + + const auto check_z = poly.list_faces_within_radius(Real3(5.0, 2.0, 0.0), 2.1); + bool find_z_2 = false; + bool find_z_3 = false; + bool find_z_4 = false; + for(const auto& found_z : check_z) + { + if(found_z.first.first == f2) {find_z_2 = true;} + if(found_z.first.first == f3) {find_z_3 = true;} + if(found_z.first.first == f4) {find_z_4 = true;} + } + BOOST_CHECK(find_z_2); + BOOST_CHECK(find_z_3); + BOOST_CHECK(find_z_4); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/ParticleSpaceRTreeImpl_test.cpp",".cpp","9162","227","#define BOOST_TEST_MODULE ""ParticleSpaceRTreeImpl_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include +#include + +using namespace ecell4; + +// a set of parameters used in the test cases below +struct Fixture +{ + typedef ParticleSpaceRTreeImpl particle_space_type; + + const Real3 edge_lengths; + const Real radius; + + Fixture() : + edge_lengths(1, 1, 1), + radius(0.005) + {} +}; + +BOOST_FIXTURE_TEST_SUITE(suite, Fixture) // submit parameters + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_constructor) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + + BOOST_CHECK_EQUAL((*space).list_species().size(), 0); + BOOST_CHECK_EQUAL((*space).num_particles(), 0); + BOOST_CHECK_EQUAL((*space).edge_lengths(), edge_lengths); + BOOST_CHECK_EQUAL((*space).volume(), 1.0); + BOOST_CHECK_EQUAL((*space).t(), 0.0); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_update_remove) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const Species sp1 = Species(""A""); + const Species sp2 = Species(""B""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.5, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); + + BOOST_CHECK(! (*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.25, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); + + BOOST_CHECK(! (*space).update_particle(pid1, Particle(sp2, edge_lengths * 0.1, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 1); + + (*space).remove_particle(pid1); + BOOST_CHECK_EQUAL((*space).num_particles(), 0); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_remove) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const ParticleID pid2 = pidgen(); + const ParticleID pid3 = pidgen(); + const Species sp1 = Species(""A""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.5, radius, 0))); + BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, edge_lengths * 0.25, radius, 0))); + BOOST_CHECK((*space).update_particle(pid3, Particle(sp1, edge_lengths * 0.75, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 3); + + (*space).remove_particle(pid2); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); + (*space).remove_particle(pid3); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + (*space).remove_particle(pid1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_exception) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + SerialIDGenerator pidgen; + const ParticleID pid1 = pidgen(); + + BOOST_CHECK_THROW((*space).remove_particle(pid1), NotFound); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_list_particles_within_radius) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const ParticleID pid2 = pidgen(); + const Species sp1 = Species(""A""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, Real3(0.5, 0.5, 0.5), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid1); + BOOST_CHECK_CLOSE(retval[0].second, 0.009 - radius, 1e-6); + } + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius, pid1).size(), 0); + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.511, 0.5, 0.5), radius).size(), 0); + + BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, Real3(0.511, 0.5, 0.5), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); + + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius).size(), 2); + (*space).remove_particle(pid1); + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid2); + BOOST_CHECK_CLOSE(retval[0].second, 0.002 - radius, 1e-6); + } +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_list_particles_within_radius_boundary_x) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const ParticleID pid2 = pidgen(); + const Species sp1 = Species(""A""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, Real3(0.005, 0.5, 0.5), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.996, 0.5, 0.5), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid1); + BOOST_CHECK_CLOSE(retval[0].second, 0.009 - radius, 1e-6); + } + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.996, 0.5, 0.5), radius, pid1).size(), 0); + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.994, 0.5, 0.5), radius).size(), 0); + + BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, Real3(0.994, 0.5, 0.5), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); + + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.996, 0.5, 0.5), radius).size(), 2); + (*space).remove_particle(pid1); + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.996, 0.5, 0.5), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid2); + BOOST_CHECK_CLOSE(retval[0].second, 0.002 - radius, 1e-6); + } +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_list_particles_within_radius_boundary_xyz) +{ + std::unique_ptr space(new particle_space_type(edge_lengths)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const ParticleID pid2 = pidgen(); + const Species sp1 = Species(""A""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, Real3(0.0025, 0.0025, 0.0025), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.9975, 0.9975, 0.9975), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid1); + BOOST_CHECK_CLOSE(retval[0].second, std::sqrt(3.0) * 0.005 - radius, 1e-6); + } + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.9975, 0.9975, 0.9975), radius, pid1).size(), 0); + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.9965, 0.9965, 0.9965), radius).size(), 0); + + BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, Real3(0.9965, 0.9965, 0.9965), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); + + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.9975, 0.9975, 0.9975), radius).size(), 2); + (*space).remove_particle(pid1); + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.9975, 0.9975, 0.9975), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid2); + BOOST_CHECK_CLOSE(retval[0].second, std::sqrt(3.0) * 0.001 - radius, 1e-6); + } +} + + + + +BOOST_AUTO_TEST_CASE(ParticleSpaceRTreeImpl_test_constructor) +{ + std::unique_ptr space(new ParticleSpaceRTreeImpl(edge_lengths)); + + BOOST_CHECK_EQUAL(space->edge_lengths()[0], edge_lengths[0]); + BOOST_CHECK_EQUAL(space->edge_lengths()[1], edge_lengths[1]); + BOOST_CHECK_EQUAL(space->edge_lengths()[2], edge_lengths[2]); +} + +BOOST_AUTO_TEST_SUITE_END() +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/NetfreeModel_test.cpp",".cpp","12367","331","#define BOOST_TEST_MODULE ""NetfreeModel_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include +#include + +using namespace ecell4; + + +BOOST_AUTO_TEST_CASE(NetfreeModel_test_constructor) +{ + NetfreeModel model; +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_test_species) +{ + NetworkModel model; + + { + Species sp1(""A""); + sp1.set_attribute(""key1"", ""value1""); + Species sp2(""B""); + sp2.set_attribute(""key1"", ""value2""); + Species sp3(""_""); + sp3.set_attribute(""key1"", ""value0""); + + model.add_species_attribute(sp1); + model.add_species_attribute(sp2); + model.add_species_attribute(sp3); + + BOOST_CHECK(model.has_species_attribute(Species(""_""))); + BOOST_CHECK(model.has_species_attribute(Species(""A""))); + BOOST_CHECK(model.has_species_attribute(Species(""B""))); + BOOST_CHECK(!model.has_species_attribute(Species(""C""))); + + Species sp4(""A""); + sp4.set_attribute(""key2"", ""value3""); + BOOST_CHECK(!model.update_species_attribute(sp4)); + } + + { + const Species sp1 = model.apply_species_attributes(Species(""A"")); + BOOST_CHECK(sp1.has_attribute(""key1"")); + BOOST_CHECK_EQUAL(sp1.get_attribute_as(""key1""), ""value1""); + BOOST_CHECK(sp1.has_attribute(""key2"")); + BOOST_CHECK_EQUAL(sp1.get_attribute_as(""key2""), ""value3""); + + const Species sp2 = model.apply_species_attributes(Species(""B"")); + BOOST_CHECK(sp2.has_attribute(""key1"")); + BOOST_CHECK_EQUAL(sp2.get_attribute_as(""key1""), ""value2""); + BOOST_CHECK(!sp2.has_attribute(""key2"")); + + const Species sp3 = model.apply_species_attributes(Species(""C"")); + BOOST_CHECK(sp3.has_attribute(""key1"")); + BOOST_CHECK_EQUAL(sp3.get_attribute_as(""key1""), ""value0""); + BOOST_CHECK(!sp3.has_attribute(""key2"")); + } + + model.remove_species_attribute(Species(""A"")); + BOOST_CHECK(!model.has_species_attribute(Species(""A""))); + BOOST_CHECK_THROW(model.remove_species_attribute(Species(""A"")), NotFound); +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_test_reaction_rule) +{ + Species sp1(""A""), sp2(""B""), sp3(""C""); + + ReactionRule rr1, rr2, rr3; + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + rr1.add_product(sp3); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + rr2.add_product(sp2); + rr3.add_reactant(sp1); + rr3.add_product(sp2); + + NetfreeModel model; + model.add_reaction_rule(rr1); + model.add_reaction_rule(rr2); + BOOST_CHECK(model.has_reaction_rule(rr1)); + BOOST_CHECK(model.has_reaction_rule(rr2)); + BOOST_CHECK(!model.has_reaction_rule(rr3)); + model.add_reaction_rule(rr3); + // BOOST_CHECK_THROW(model.add_reaction_rule(rr1), AlreadyExists); //XXX: + model.remove_reaction_rule(rr1); + BOOST_CHECK_THROW(model.remove_reaction_rule(rr1), NotFound); + model.remove_reaction_rule(rr3); + model.remove_reaction_rule(rr2); +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_test_query_reaction_rules1) +{ + Species sp1(""A""), sp2(""B""), sp3(""C""); + + ReactionRule rr1, rr2, rr3, rr4; + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + rr1.add_product(sp3); + + rr2.add_reactant(sp3); + rr2.add_product(sp1); + rr2.add_product(sp2); + + rr3.add_reactant(sp1); + rr3.add_product(sp2); + + rr4.add_reactant(sp1); + rr4.add_product(sp3); + + NetfreeModel model; + model.add_reaction_rule(rr1); + model.add_reaction_rule(rr2); + model.add_reaction_rule(rr3); + model.add_reaction_rule(rr4); + + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp1).size(), 2); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp3).size(), 1); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp2).size(), 0); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp1, sp2).size(), 1); + BOOST_CHECK((*(model.query_reaction_rules(sp1, sp2).begin())) == rr1); +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_test_query_reaction_rules2) +{ + Species sp1(""A""), sp2(""B""); + + ReactionRule rr1; + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + + NetfreeModel model; + model.add_reaction_rule(rr1); + + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp1, sp2).size(), 1); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp2, sp1).size(), 1); +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_generation1) +{ + NetfreeModel nfm; + nfm.add_reaction_rule( + create_synthesis_reaction_rule(Species(""X(p,q=a)""), 1.0)); + nfm.add_reaction_rule( + create_unimolecular_reaction_rule(Species(""X(q=a)""), Species(""X(q=b)""), 1.0)); + nfm.add_reaction_rule( + create_unbinding_reaction_rule( + Species(""X(p^1).X(p^1)""), Species(""X(p)""), Species(""X(p)""), 1.0)); + nfm.add_reaction_rule( + create_binding_reaction_rule( + Species(""X(p)""), Species(""X(p)""), Species(""X(p^1).X(p^1)""), 1.0)); + + std::vector seeds(1); + seeds[0] = Species(""X(p^1,q=a).X(p^1,q=a)""); + // seeds[1] = Species(""X(p,q=a)""); + + std::shared_ptr nwm(nfm.expand(seeds, 10)); + + // for (NetworkModel::reaction_rule_container_type::const_iterator + // i((*nwm).reaction_rules().begin()); i != (*nwm).reaction_rules().end(); ++i) + // { + // NetworkModel::reaction_rule_container_type::difference_type + // idx(std::distance((*nwm).reaction_rules().begin(), i)); + // std::cout << ""["" << idx << ""]: "" << (*i).as_string() << std::endl; + // } + + BOOST_CHECK_EQUAL((*nwm).reaction_rules().size(), 10); +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_generation2) +{ + NetfreeModel nfm; + nfm.add_reaction_rule( + create_synthesis_reaction_rule(Species(""X(l,r)""), 1.0)); + nfm.add_reaction_rule( + create_binding_reaction_rule( + Species(""X(r)""), Species(""X(l)""), Species(""X(r^1).X(l^1)""), 1.0)); + nfm.add_reaction_rule( + create_unbinding_reaction_rule( + Species(""X(r^1).X(l^1)""),Species(""X(r)""), Species(""X(l)""), 1.0)); + + std::vector seeds(0); + std::map max_stoich; + max_stoich[Species(""X"")] = 5; + + std::shared_ptr nwm(nfm.expand(seeds, 10, max_stoich)); + + // for (NetworkModel::reaction_rule_container_type::const_iterator + // i((*nwm).reaction_rules().begin()); i != (*nwm).reaction_rules().end(); ++i) + // { + // NetworkModel::reaction_rule_container_type::difference_type + // idx(std::distance((*nwm).reaction_rules().begin(), i)); + // std::cout << ""["" << idx << ""]: "" << (*i).as_string() << std::endl; + // } + + BOOST_CHECK_EQUAL((*nwm).reaction_rules().size(), 13); +} + +// BOOST_AUTO_TEST_CASE(NetfreeModel_query_reaction_rules3) +// { +// } + +BOOST_AUTO_TEST_CASE(NetfreeModel_generation3) +{ + NetfreeModel m1; + m1.add_reaction_rule( + create_binding_reaction_rule( + Species(""A(r)""), Species(""A(l)""), Species(""A(r^1).A(l^1)""), 1.0)); + + std::vector const retval1 = m1.query_reaction_rules(Species(""A(l, r)""), Species(""A(l, r)"")); + BOOST_CHECK_EQUAL(retval1.size(), 1); + BOOST_CHECK_EQUAL(retval1[0].k(), 2.0); + BOOST_CHECK_EQUAL(retval1[0].reactants().size(), 2); + BOOST_CHECK_EQUAL(retval1[0].reactants()[0], Species(""A(l,r)"")); + BOOST_CHECK_EQUAL(retval1[0].reactants()[1], Species(""A(l,r)"")); + BOOST_CHECK_EQUAL(retval1[0].products().size(), 1); + BOOST_CHECK_EQUAL(retval1[0].products()[0], Species(""A(l,r^1).A(l^1,r)"")); + + std::vector seeds1(1, Species(""A(l, r)"")); + std::map max_stoich; + max_stoich[Species(""A"")] = 4; + std::shared_ptr m2(m1.expand(seeds1, 100, max_stoich)); + std::vector const& reaction_rules1 = m2->reaction_rules(); + BOOST_CHECK_EQUAL(reaction_rules1.size(), 4); + BOOST_CHECK_EQUAL(reaction_rules1[0].k(), 2.0); + BOOST_CHECK_EQUAL(reaction_rules1[1].k(), 2.0); + BOOST_CHECK_EQUAL(reaction_rules1[2].k(), 2.0); + BOOST_CHECK_EQUAL(reaction_rules1[3].k(), 2.0); + + NetfreeModel m3; + m3.add_reaction_rule( + create_binding_reaction_rule( + Species(""A(r)""), Species(""A(r)""), Species(""A(r^1).A(r^1)""), 1.0)); + + std::vector const retval2 = m3.query_reaction_rules(Species(""A(r)""), Species(""A(r)"")); + BOOST_CHECK_EQUAL(retval2.size(), 1); + BOOST_CHECK_EQUAL(retval2[0].k(), 1.0); + BOOST_CHECK_EQUAL(retval2[0].reactants().size(), 2); + BOOST_CHECK_EQUAL(retval2[0].reactants()[0], Species(""A(r)"")); + BOOST_CHECK_EQUAL(retval2[0].reactants()[1], Species(""A(r)"")); + BOOST_CHECK_EQUAL(retval2[0].products().size(), 1); + BOOST_CHECK_EQUAL(retval2[0].products()[0], Species(""A(r^1).A(r^1)"")); + + std::vector const retval3 = m3.query_reaction_rules(Species(""A(r=u)""), Species(""A(r=p)"")); + BOOST_CHECK_EQUAL(retval3.size(), 1); + BOOST_CHECK_EQUAL(retval3[0].k(), 1.0); + BOOST_CHECK_EQUAL(retval3[0].reactants().size(), 2); + BOOST_CHECK_EQUAL(retval3[0].reactants()[0], Species(""A(r=u)"")); + BOOST_CHECK_EQUAL(retval3[0].reactants()[1], Species(""A(r=p)"")); + BOOST_CHECK_EQUAL(retval3[0].products().size(), 1); + BOOST_CHECK_EQUAL(retval3[0].products()[0], Species(""A(r=p^1).A(r=u^1)"")); + + NetfreeModel m4; + m4.add_reaction_rule( + create_binding_reaction_rule( + Species(""_(b)""), Species(""_(b)""), Species(""_(b^1)._(b^1)""), 1.0)); + m4.add_reaction_rule( + create_unbinding_reaction_rule( + Species(""_(b^1)._(b^1)""), Species(""_(b)""), Species(""_(b)""), 1.0)); + + std::vector const retval4 = m4.query_reaction_rules(Species(""A(b^1).A(b^1)"")); + BOOST_CHECK_EQUAL(retval4.size(), 1); + BOOST_CHECK_EQUAL(retval4[0].k(), 1.0); + BOOST_CHECK_EQUAL(retval4[0].reactants().size(), 1); + BOOST_CHECK_EQUAL(retval4[0].reactants()[0], Species(""A(b^1).A(b^1)"")); + BOOST_CHECK_EQUAL(retval4[0].products().size(), 2); + BOOST_CHECK_EQUAL(retval4[0].products()[0], Species(""A(b)"")); + BOOST_CHECK_EQUAL(retval4[0].products()[1], Species(""A(b)"")); + + std::vector seeds2(1, Species(""A(b)"")); + std::shared_ptr m5(m4.expand(seeds2)); + std::vector const& reaction_rules2 = m5->reaction_rules(); + BOOST_CHECK_EQUAL(reaction_rules2.size(), 2); + + std::vector seeds3(2); + seeds3[0] = Species(""A(b)""); + seeds3[1] = Species(""B(b)""); + std::shared_ptr m6(m4.expand(seeds3)); + std::vector const& reaction_rules3 = m6->reaction_rules(); + BOOST_CHECK_EQUAL(reaction_rules3.size(), 6); + for (std::vector::const_iterator i(reaction_rules3.begin()); + i != reaction_rules3.end(); ++i) + { + BOOST_CHECK_EQUAL((*i).k(), 1.0); + } +} + +BOOST_AUTO_TEST_CASE(NetfreeModel_test_proceed) +{ + { + NetfreeModel model; + Species A(""A""); + model.add_species_attribute(A, false); + A.set_attribute(""foo"", ""bar""); + model.add_species_attribute(A, false); + BOOST_CHECK(!model.apply_species_attributes(Species(""A"")).has_attribute(""foo"")); + } + { + NetfreeModel model; + Species A(""A""); + model.add_species_attribute(A, true); + A.set_attribute(""foo"", ""bar""); + model.add_species_attribute(A, false); + BOOST_CHECK(model.apply_species_attributes(Species(""A"")).has_attribute(""foo"")); + } + { + NetfreeModel model; + Species X(""_""); + X.set_attribute(""foo"", ""bar""); + X.set_attribute(""hoge"", ""fuga""); + model.add_species_attribute(X, true); + Species A(""A""); + A.set_attribute(""foo"", ""BAR""); + model.add_species_attribute(A, false); + BOOST_CHECK(model.apply_species_attributes(Species(""A"")).has_attribute(""foo"")); + BOOST_CHECK_EQUAL(model.apply_species_attributes(Species(""A"")).get_attribute_as(""foo""), ""BAR""); + BOOST_CHECK(model.apply_species_attributes(Species(""A"")).has_attribute(""hoge"")); + BOOST_CHECK(model.apply_species_attributes(Species(""B"")).has_attribute(""foo"")); + BOOST_CHECK_EQUAL(model.apply_species_attributes(Species(""B"")).get_attribute_as(""foo""), ""bar""); + BOOST_CHECK(model.apply_species_attributes(Species(""B"")).has_attribute(""hoge"")); + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/NetworkModel_test.cpp",".cpp","5969","178","#define BOOST_TEST_MODULE ""NetworkModel_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include + +using namespace ecell4; + + +BOOST_AUTO_TEST_CASE(NetworkModel_test_constructor) +{ + NetworkModel model; +} + +BOOST_AUTO_TEST_CASE(NetworkModel_test_species) +{ + NetworkModel model; + + { + Species sp1(""A""); + sp1.set_attribute(""key1"", ""value1""); + Species sp2(""B""); + sp2.set_attribute(""key1"", ""value2""); + Species sp3(""_""); + sp3.set_attribute(""key1"", ""value0""); + + model.add_species_attribute(sp1); + model.add_species_attribute(sp2); + model.add_species_attribute(sp3); + + BOOST_CHECK(model.has_species_attribute(Species(""_""))); + BOOST_CHECK(model.has_species_attribute(Species(""A""))); + BOOST_CHECK(model.has_species_attribute(Species(""B""))); + BOOST_CHECK(!model.has_species_attribute(Species(""C""))); + + Species sp4(""A""); + sp4.set_attribute(""key2"", ""value3""); + BOOST_CHECK(!model.update_species_attribute(sp4)); + } + + { + const Species sp1 = model.apply_species_attributes(Species(""A"")); + BOOST_CHECK(sp1.has_attribute(""key1"")); + BOOST_CHECK_EQUAL(sp1.get_attribute_as(""key1""), ""value1""); + BOOST_CHECK(sp1.has_attribute(""key2"")); + BOOST_CHECK_EQUAL(sp1.get_attribute_as(""key2""), ""value3""); + + const Species sp2 = model.apply_species_attributes(Species(""B"")); + BOOST_CHECK(sp2.has_attribute(""key1"")); + BOOST_CHECK_EQUAL(sp2.get_attribute_as(""key1""), ""value2""); + BOOST_CHECK(!sp2.has_attribute(""key2"")); + + const Species sp3 = model.apply_species_attributes(Species(""C"")); + BOOST_CHECK(sp3.has_attribute(""key1"")); + BOOST_CHECK_EQUAL(sp3.get_attribute_as(""key1""), ""value0""); + BOOST_CHECK(!sp3.has_attribute(""key2"")); + } + + model.remove_species_attribute(Species(""A"")); + BOOST_CHECK(!model.has_species_attribute(Species(""A""))); + BOOST_CHECK_THROW(model.remove_species_attribute(Species(""A"")), NotFound); +} + +BOOST_AUTO_TEST_CASE(NetworkModel_test_reaction_rule) +{ + Species sp1(""A""), sp2(""B""), sp3(""C""); + + ReactionRule rr1, rr2, rr3; + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + rr1.add_product(sp3); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + rr2.add_product(sp2); + rr3.add_reactant(sp1); + rr3.add_product(sp2); + + NetworkModel model; + model.add_reaction_rule(rr1); + model.add_reaction_rule(rr2); + BOOST_CHECK(model.has_reaction_rule(rr1)); + BOOST_CHECK(model.has_reaction_rule(rr2)); + BOOST_CHECK(!model.has_reaction_rule(rr3)); + model.add_reaction_rule(rr3); + // BOOST_CHECK_THROW(model.add_reaction_rule(rr1), AlreadyExists); //XXX: + model.remove_reaction_rule(rr1); + BOOST_CHECK_THROW(model.remove_reaction_rule(rr1), NotFound); + model.remove_reaction_rule(rr3); + model.remove_reaction_rule(rr2); +} + +BOOST_AUTO_TEST_CASE(NetworkModel_test_query_reaction_rules1) +{ + Species sp1(""A""), sp2(""B""), sp3(""C""); + + ReactionRule rr1, rr2, rr3, rr4; + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + rr1.add_product(sp3); + rr2.add_reactant(sp3); + rr2.add_product(sp1); + rr2.add_product(sp2); + rr3.add_reactant(sp1); + rr3.add_product(sp2); + rr4.add_reactant(sp1); + rr4.add_product(sp3); + + NetworkModel model; + model.add_reaction_rule(rr1); + model.add_reaction_rule(rr2); + model.add_reaction_rule(rr3); + model.add_reaction_rule(rr4); + + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp1).size(), 2); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp3).size(), 1); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp2).size(), 0); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp1, sp2).size(), 1); + BOOST_CHECK((*(model.query_reaction_rules(sp1, sp2).begin())) == rr1); +} + +BOOST_AUTO_TEST_CASE(NetworkModel_test_query_reaction_rules2) +{ + Species sp1(""A""), sp2(""B""); + + ReactionRule rr1; + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + + NetworkModel model; + model.add_reaction_rule(rr1); + + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp1, sp2).size(), 1); + BOOST_CHECK_EQUAL(model.query_reaction_rules(sp2, sp1).size(), 1); +} + +BOOST_AUTO_TEST_CASE(NetworkModel_test_proceed) +{ + { + NetworkModel model; + Species A(""A""); + model.add_species_attribute(A, false); + A.set_attribute(""foo"", ""bar""); + model.add_species_attribute(A, false); + BOOST_CHECK(!model.apply_species_attributes(Species(""A"")).has_attribute(""foo"")); + } + { + NetworkModel model; + Species A(""A""); + model.add_species_attribute(A, true); + A.set_attribute(""foo"", ""bar""); + model.add_species_attribute(A, false); + BOOST_CHECK(model.apply_species_attributes(Species(""A"")).has_attribute(""foo"")); + } + { + NetworkModel model; + Species X(""_""); + X.set_attribute(""foo"", ""bar""); + X.set_attribute(""hoge"", ""fuga""); + model.add_species_attribute(X, true); + Species A(""A""); + A.set_attribute(""foo"", ""BAR""); + model.add_species_attribute(A, false); + BOOST_CHECK(model.apply_species_attributes(Species(""A"")).has_attribute(""foo"")); + BOOST_CHECK_EQUAL(model.apply_species_attributes(Species(""A"")).get_attribute_as(""foo""), ""BAR""); + BOOST_CHECK(model.apply_species_attributes(Species(""A"")).has_attribute(""hoge"")); + BOOST_CHECK(model.apply_species_attributes(Species(""B"")).has_attribute(""foo"")); + BOOST_CHECK_EQUAL(model.apply_species_attributes(Species(""B"")).get_attribute_as(""foo""), ""bar""); + BOOST_CHECK(model.apply_species_attributes(Species(""B"")).has_attribute(""hoge"")); + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/STLIO_test.cpp",".cpp","4592","110","#define BOOST_TEST_MODULE ""STLIO_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include + +using ecell4::Real; +using ecell4::Real3; +using ecell4::Triangle; + +BOOST_AUTO_TEST_CASE(test_io_ascii) +{ + boost::random::mt19937 mt(123456789); + boost::random::uniform_real_distribution uni(0.0, 100.0); + + std::vector triangles; + for(std::size_t i=0; i<100; ++i) + { + const Real3 v0(uni(mt), uni(mt), uni(mt)); + const Real3 v1(uni(mt), uni(mt), uni(mt)); + const Real3 v2(uni(mt), uni(mt), uni(mt)); + triangles.push_back(Triangle(v0, v1, v2)); + } + + ecell4::write_stl_format( + ""STLIO_test_asc.stl"", ecell4::STLFormat::Ascii, triangles); + + const std::vector after_io = ecell4::read_stl_format( + ""STLIO_test_asc.stl"", ecell4::STLFormat::Ascii); + + BOOST_REQUIRE(after_io.size() == triangles.size()); + for(std::size_t i=0; i uni(0.0, 100.0); + + std::vector triangles; + for(std::size_t i=0; i<100; ++i) + { + const Real3 v0(uni(mt), uni(mt), uni(mt)); + const Real3 v1(uni(mt), uni(mt), uni(mt)); + const Real3 v2(uni(mt), uni(mt), uni(mt)); + triangles.push_back(Triangle(v0, v1, v2)); + } + + ecell4::write_stl_format( + ""STLIO_test_bin.stl"", ecell4::STLFormat::Binary, triangles); + + const std::vector after_io = ecell4::read_stl_format( + ""STLIO_test_bin.stl"", ecell4::STLFormat::Binary); + + BOOST_REQUIRE(after_io.size() == triangles.size()); + for(std::size_t i=0; i +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +// #include ""../types.hpp"" +// #include ""../CompartmentSpace.hpp"" +#include +#include + +using namespace ecell4; + +template +void CompartmentSpace_test_volume_template() +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + Timpl_ target(edge_lengths); + const Real new_volume(2 * target.volume()); + target.set_volume(new_volume); + BOOST_CHECK_EQUAL(target.volume(), new_volume); +} + +BOOST_AUTO_TEST_CASE(CompartmentSpace_test_volume) +{ + CompartmentSpace_test_volume_template(); +} + +template +void CompartmentSpace_test_species_template() +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + Timpl_ target(edge_lengths); + + Species sp1(""A""), sp2(""B""), sp3(""C""); + // target.add_species(sp1); + // target.add_species(sp2); + // BOOST_CHECK(target.has_species(sp1)); + // BOOST_CHECK(target.has_species(sp2)); + // BOOST_CHECK(!target.has_species(sp3)); + // target.add_species(sp3); + // BOOST_CHECK(target.has_species(sp3)); + // BOOST_CHECK(target.num_species() == 3); + + // target.remove_species(sp2); + // BOOST_CHECK(!target.has_species(sp2)); + // BOOST_CHECK_THROW(target.remove_species(sp2), NotFound); + // BOOST_CHECK(target.has_species(sp1)); + // BOOST_CHECK(target.has_species(sp3)); + + BOOST_CHECK(target.num_molecules(sp1) == 0); + target.add_molecules(sp1, 30); + BOOST_CHECK(target.num_molecules(sp1) == 30); + target.remove_molecules(sp1, 10); + BOOST_CHECK(target.num_molecules(sp1) == 20); +} + +BOOST_AUTO_TEST_CASE(CompartmentSpace_test_species) +{ + CompartmentSpace_test_species_template(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/ReactionRule_test.cpp",".cpp","19311","475","#define BOOST_TEST_MODULE ""ReactionRule_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include +#include +#include + +using namespace ecell4; + + +BOOST_AUTO_TEST_CASE(ReactionRule_test_constructor) +{ + ReactionRule rr; +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_k) +{ + const Real epsrel(1e-6); + const Real k(1.5); + ReactionRule rr; + rr.set_k(0); + rr.set_k(k); + BOOST_CHECK_CLOSE(rr.k(), k, k * epsrel); + BOOST_CHECK_THROW(rr.set_k(-k), std::invalid_argument); +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_reactants) +{ + ReactionRule rr; + Species sp1(""A""), sp2(""B""); + rr.add_reactant(sp1); + rr.add_reactant(sp2); + rr.add_reactant(sp1); + + const ReactionRule::reactant_container_type& reactants(rr.reactants()); + BOOST_CHECK_EQUAL(reactants.size(), 3); + BOOST_CHECK_EQUAL(std::count(reactants.begin(), reactants.end(), sp1), 2); + BOOST_CHECK_EQUAL(std::count(reactants.begin(), reactants.end(), sp2), 1); +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_products) +{ + ReactionRule rr; + Species sp1(""A""), sp2(""B""); + rr.add_product(sp1); + rr.add_product(sp2); + rr.add_product(sp1); + + const ReactionRule::product_container_type& products(rr.products()); + BOOST_CHECK_EQUAL(products.size(), 3); + BOOST_CHECK_EQUAL(std::count(products.begin(), products.end(), sp1), 2); + BOOST_CHECK_EQUAL(std::count(products.begin(), products.end(), sp2), 1); +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_compare) +{ + ReactionRule rr1, rr2, rr3, rr4, rr5; + Species sp1(""A""), sp2(""B""), sp3(""C""), sp4(""D""); + + rr1.add_reactant(sp1); + rr1.add_reactant(sp2); + rr1.add_product(sp3); + rr1.set_k(1.5); + + rr2.add_reactant(sp1); + rr2.add_reactant(sp3); + rr2.add_product(sp3); + rr2.set_k(1.5); + + rr3.add_reactant(sp1); + rr3.add_reactant(sp2); + rr3.add_product(sp4); + rr3.set_k(1.5); + + rr4.add_reactant(sp2); + rr4.add_reactant(sp1); + rr4.add_product(sp3); + rr4.set_k(5.0); + + rr5.add_reactant(sp1); + rr5.add_reactant(sp2); + rr5.add_product(sp3); + rr5.set_k(5.0); + + BOOST_CHECK(rr1 == rr1); + BOOST_CHECK(rr1 != rr2); + BOOST_CHECK(rr1 != rr3); + BOOST_CHECK(rr1 != rr4); + BOOST_CHECK(rr1 == rr5); +} + +void check_reaction_rule_generation( + const ReactionRule& rr, const std::vector& reactants, + const std::vector& ans, + const std::string& filename, const unsigned int& lineno) +{ + const std::vector res = rr.generate(reactants); + + BOOST_CHECK_MESSAGE(res.size() == ans.size(), """" << filename << ""("" << lineno << ""): check res.size() == ans.size() failed ["" << res.size() << "" != "" << ans.size() << ""]""); + + std::vector::difference_type> done; + done.reserve(res.size()); + for (std::vector::const_iterator i(res.begin()); + i != res.end(); ++i) + { + bool found = false; + const ReactionRule formatted = format_reaction_rule_with_nosort(*i); + for (std::vector::const_iterator j(ans.begin()); + j != ans.end(); ++j) + { + if (formatted == (*j) && formatted.k() == (*j).k()) + { + std::vector::difference_type idx = std::distance(ans.begin(), j); + if (std::find(done.begin(), done.end(), idx) == done.end()) + { + found = true; + done.push_back(idx); + break; + } + } + } + + BOOST_CHECK_MESSAGE(found, """" << filename << ""("" << lineno << ""): A result ["" << (*i).as_string() << ""] is not in the list""); + } +} + +#define ECELL4_TEST_REACTION_RULE_GENERATION( rr, reactants, ans ) \ + check_reaction_rule_generation(rr, reactants, ans, __FILE__, __LINE__) + + +BOOST_AUTO_TEST_CASE(ReactionRule_test_generate1) +{ + { + const ReactionRule rr = create_synthesis_reaction_rule(Species(""A""), 1.0); + std::vector reactants; // XXX: empty + std::vector ans; + ans.push_back(rr); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_generate2) +{ + { + const ReactionRule rr = create_binding_reaction_rule( + Species(""_1(b)""), Species(""_1(b)""), Species(""_1(b^1)._1(b^1)""), 1.0); + + ReactionRule::reactant_container_type reactants; + reactants.push_back(Species(""A(a^1,b).B(a^1,b)"")); + reactants.push_back(Species(""B(a,b)"")); + + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_binding_reaction_rule( + reactants[0], reactants[1], Species(""A(a^1,b).B(a^1,b^3).B(a,b^3)""), 1.0))); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + + { + const ReactionRule rr = create_binding_reaction_rule( + Species(""A(b)""), Species(""B(b)""), Species(""A(b^1).B(b^1)""), 1.0); + + ReactionRule::reactant_container_type reactants; + reactants.push_back(Species(""A(a^1,b).A(a^1,b)"")); + reactants.push_back(Species(""B(a^1,b).B(a^1,b^2).B(a^2,b)"")); + + std::vector ans; + const ReactionRule _ans1 = format_reaction_rule_with_nosort(create_binding_reaction_rule( + reactants[0], reactants[1], Species(""A(a^1,b^4).A(a^1,b).B(a^2,b^4).B(a^2,b^3).B(a^3,b)""), 1.0)); + ans.push_back(_ans1); + ans.push_back(_ans1); + const ReactionRule _ans2 = format_reaction_rule_with_nosort(create_binding_reaction_rule( + reactants[0], reactants[1], Species(""A(a^1,b^4).A(a^1,b).B(a^2,b).B(a^2,b^3).B(a^3,b^4)""), 1.0)); + ans.push_back(_ans2); + ans.push_back(_ans2); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + + std::vector retval; + + { + const ReactionRule rr = create_unimolecular_reaction_rule( + Species(""A""), Species(""B""), 1.0); + ReactionRule::reactant_container_type reactants; + reactants.push_back(Species(""A"")); + std::vector ans; + ans.push_back(rr); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + + { + const ReactionRule rr = create_unbinding_reaction_rule( + Species(""A(b^1).B(b^1)""), Species(""A(b)""), Species(""B(b)""), 1.0); + ReactionRule::reactant_container_type reactants; + reactants.push_back( + Species(""A(a^1,b^5).A(a^1,b^4).B(a^2,b).B(a^2,b^3).B(a^3,b^4).B(a,b^5)"")); + + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + reactants[0], Species(""A(a^1,b).A(a^1,b^4).B(a^2,b).B(a^2,b^3).B(a^3,b^4)""), Species(""B(a,b)""), 1.0))); + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + reactants[0], Species(""A(a^1,b^5).A(a^1,b).B(a,b^5)""), Species(""B(a^2,b).B(a^2,b^3).B(a^3,b)""), 1.0))); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_recursive_generation1) +{ + ReactionRule rr1; + rr1.add_reactant(Species(""X(r^1).X(l^1)"")); + rr1.add_product(Species(""X(r)"")); + rr1.add_product(Species(""X(l)"")); + rr1.set_k(1.0); + const Species sp1(""X(l,r^1).X(l^1,r^2).X(l^2,r^3).X(l^3,r^4).X(l^4,r)""); + + // ReactionRuleExpressionMatcher rrexp(rr1); + // BOOST_CHECK(rrexp.match(sp1)); + + // unsigned int i(0); + // do { + // ++i; + // std::vector products(rrexp.generate()); + // // const ReactionRule tmp(rrexp.reactants(), products, rr1.k()); + // // std::cerr << ""GEN: "" << tmp.as_string() << std::endl; + // } while (rrexp.next()); + + // BOOST_CHECK_EQUAL(i, 4); + + std::vector reactants; + reactants.push_back(sp1); + std::vector retval(rr1.generate(reactants)); + BOOST_CHECK_EQUAL(retval.size(), 4); +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_generate3) +{ + { + const ReactionRule rr = create_unbinding_reaction_rule( + Species(""A(b=u^1).A(b=u^1)""), Species(""A(b=u)""), Species(""A(b=u)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b=u^1).A(b=u^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(rr)); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_unbinding_reaction_rule( + Species(""A(b=u^1).A(b=u^1)""), Species(""A(b=u)""), Species(""A(b=p)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b=u^1).A(b=u^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(rr)); + // ans.push_back(format_reaction_rule_with_nosort(rr)); + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + Species(""A(b=u^1).A(b=u^1)""), Species(""A(b=p)""), Species(""A(b=u)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_unbinding_reaction_rule( + Species(""A(b^1,c^2).A(b^1,c^3).B(l^2,r^4).B(l^3,r^4)""), + Species(""A(b^1,c).A(b^1,c)""), + Species(""B(l,r^1).B(l,r^1)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1,c^2).A(b^1,c^3).B(l^2,r^4).B(l^3,r^4)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + reactants[0], Species(""A(b^1,c).A(b^1,c)""), Species(""B(l,r^1).B(l,r^1)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_binding_reaction_rule( + Species(""A(b^1,c).A(b^1,c)""), Species(""B(l,r^1).B(l,r^1)""), + Species(""A(b^1,c^2).A(b^1,c^3).B(l^2,r^4).B(l^3,r^4)""), 1.0); + + ReactionRule::reactant_container_type reactants(2); + reactants[0] = Species(""A(b^1,c).A(b^1,c)""); + reactants[1] = Species(""B(l,r^1).B(l,r^1)""); + + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(rr)); + ans.push_back(format_reaction_rule_with_nosort(rr)); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_unbinding_reaction_rule( + Species(""_(b^1)._(b^1)""), Species(""_(b)""), Species(""_(b)""), 1.0); + + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).A(b^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + Species(""A(b^1).A(b^1)""), Species(""A(b)""), Species(""A(b)""), 1.0))); + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_unbinding_reaction_rule( + Species(""_1(b^1)._1(b^1)""), Species(""_1(b)""), Species(""_1(b)""), 1.0); + + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).B(b^1)"")); + std::vector ans; + + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_generate4) +{ + { + const ReactionRule rr = create_unimolecular_reaction_rule( + Species(""A(b^1).B(b^1)""), Species(""A(b)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b=u^1).B(b^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unimolecular_reaction_rule( + reactants[0], Species(""A(b=u)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""B""), 1.0); + rr.set_policy(ReactionRule::POLICY_IMPLICIT); + + ReactionRule::reactant_container_type reactants(1, Species(""A(b=u^1).B(b^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unimolecular_reaction_rule( + reactants[0], Species(""A(b=u)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""B""), 1.0); + rr.set_policy(ReactionRule::POLICY_DESTROY); + + ReactionRule::reactant_container_type reactants(1, Species(""A(b=u^1).B(b^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_degradation_reaction_rule(reactants[0], 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_unimolecular_reaction_rule( + Species(""A(b^1).A(b^1)""), Species(""A(b)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).A(b^1)"")); + std::vector ans; + const ReactionRule _ans = format_reaction_rule_with_nosort(create_unimolecular_reaction_rule( + reactants[0], Species(""A(b)""), 1.0)); + ans.push_back(_ans); + ans.push_back(_ans); //XXX: res should have two ReactionRules as shown here + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""A(b^1).A(b^1)""), 1.0); + + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).A(b^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_degradation_reaction_rule(reactants[0], 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_unimolecular_reaction_rule( + Species(""A(b=_1^1).B(b^1)""), Species(""A(b=_1^1).C(b=_1^1)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b=u^1).B(b^1)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unimolecular_reaction_rule( + reactants[0], Species(""A(b=u^1).C(b=u^1)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_generate5) +{ + { + const ReactionRule rr = create_binding_reaction_rule( + Species(""X(r)""), Species(""X(l)""), Species(""X(r^1).X(l^1)""), 1.0); + ReactionRule::reactant_container_type reactants(2, Species(""X(l,r)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_binding_reaction_rule( + reactants[0], reactants[1], Species(""X(l,r^1).X(l^1,r)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_binding_reaction_rule( + Species(""X(r)""), Species(""X(l)""), Species(""X(r^1).X(l^1)""), 1.0); + ReactionRule::reactant_container_type reactants; + reactants.push_back(Species(""X(l,r^1).X(l^1,r)"")); + reactants.push_back(Species(""X(l,r)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_binding_reaction_rule( + reactants[0], reactants[1], Species(""X(l,r^1).X(l^1,r^2).X(l^2,r)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_unbinding_reaction_rule( + Species(""X(r^1).X(l^1)""),Species(""X(r)""), Species(""X(l)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""X(l,r^1).X(l^1,r)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + reactants[0], Species(""X(l,r)""), Species(""X(l,r)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + const ReactionRule rr = create_unbinding_reaction_rule( + Species(""X(r^1).X(l^1)""),Species(""X(r)""), Species(""X(l)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""X(l,r^1).X(l^1,r^2).X(l^2,r)"")); + std::vector ans; + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + reactants[0], Species(""X(l,r^1).X(l^1,r)""), Species(""X(l,r)""), 1.0))); + ans.push_back(format_reaction_rule_with_nosort(create_unbinding_reaction_rule( + reactants[0], Species(""X(l,r)""), Species(""X(l,r^1).X(l^1,r)""), 1.0))); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } +} + +BOOST_AUTO_TEST_CASE(ReactionRule_test_generate6) +{ + { + ReactionRule rr = create_degradation_reaction_rule(Species(""A""), 1.0); + rr.set_policy(ReactionRule::POLICY_IMPLICIT); + ReactionRule::reactant_container_type reactants(1, Species(""A(b)"")); + std::vector ans; + const ReactionRule _ans = format_reaction_rule_with_nosort( + create_degradation_reaction_rule(reactants[0], 1.0)); + ans.push_back(_ans); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""A""), 1.0); + rr.set_policy(ReactionRule::POLICY_IMPLICIT); + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).B(b^1)"")); + std::vector ans; + const ReactionRule _ans = format_reaction_rule_with_nosort( + create_unimolecular_reaction_rule(reactants[0], Species(""B(b)""), 1.0)); + ans.push_back(_ans); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""A""), 1.0); + rr.set_policy(ReactionRule::POLICY_IMPLICIT); + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).A(b^1)"")); + std::vector ans; + const ReactionRule _ans = format_reaction_rule_with_nosort( + create_unimolecular_reaction_rule(reactants[0], Species(""A(b)""), 1.0)); + ans.push_back(_ans); + ans.push_back(_ans); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""A(b^1).A(b^1)""), 1.0); + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).A(b^1)"")); + std::vector ans; + const ReactionRule _ans = format_reaction_rule_with_nosort( + create_degradation_reaction_rule(reactants[0], 1.0)); + ans.push_back(_ans); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } + { + ReactionRule rr = create_degradation_reaction_rule(Species(""A""), 1.0); + rr.set_policy(ReactionRule::POLICY_DESTROY); + ReactionRule::reactant_container_type reactants(1, Species(""A(b^1).A(b^1)"")); + std::vector ans; + const ReactionRule _ans = format_reaction_rule_with_nosort( + create_degradation_reaction_rule(reactants[0], 1.0)); + ans.push_back(_ans); + ECELL4_TEST_REACTION_RULE_GENERATION(rr, reactants, ans); + } +} + +#undef ECELL4_TEST_REACTION_RULE_GENERATION +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/extras_test.cpp",".cpp","4838","98","#define BOOST_TEST_MODULE ""extras_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include + +using namespace ecell4; + + +BOOST_AUTO_TEST_CASE(extras_test_) +{ + const extras::VersionInformation vinfo = extras::parse_version_information(""ecell4-test-1.2.3""); + + BOOST_CHECK_EQUAL(vinfo.header, ""ecell4-test-""); + BOOST_CHECK_EQUAL(vinfo.majorno, 1); + BOOST_CHECK_EQUAL(vinfo.minorno, 2); + BOOST_CHECK_EQUAL(vinfo.patchno, 3); +} + +BOOST_AUTO_TEST_CASE(DimensionAttributeTest) +{ + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(Species(""A"")); + model->add_species_attribute(Species(""B"", 1.0, 0.0, ""A"")); + model->add_species_attribute(Species(""C"", 1.0, 0.0, """", 2)); + model->add_species_attribute(Species(""D"", 1.0, 0.0, ""C"")); + + BOOST_CHECK_EQUAL(extras::get_dimension_from_model(Species(""A""), model), Shape::THREE); + BOOST_CHECK_EQUAL(extras::get_dimension_from_model(Species(""B""), model), Shape::THREE); + BOOST_CHECK_EQUAL(extras::get_dimension_from_model(Species(""C""), model), Shape::TWO); + BOOST_CHECK_EQUAL(extras::get_dimension_from_model(Species(""D""), model), Shape::TWO); + BOOST_CHECK_EQUAL(extras::get_dimension_from_model(Species(""E""), model), Shape::THREE); + // BOOST_CHECK_THROW(extras::get_dimension_from_model(Species(""E""), model), NotFound); +} + +BOOST_AUTO_TEST_CASE(VersionInformationTest) +{ + { + const extras::VersionInformation vinfo1 = extras::parse_version_information(""ecell4-test-1.2.3""); + BOOST_CHECK_EQUAL(vinfo1.header, ""ecell4-test-""); + BOOST_CHECK_EQUAL(vinfo1.majorno, 1); + BOOST_CHECK_EQUAL(vinfo1.minorno, 2); + BOOST_CHECK_EQUAL(vinfo1.patchno, 3); + BOOST_CHECK_EQUAL(vinfo1.devno, -1); + } + { + const extras::VersionInformation vinfo1 = extras::parse_version_information(""ecell4-test-1.2""); + BOOST_CHECK_EQUAL(vinfo1.header, ""ecell4-test-""); + BOOST_CHECK_EQUAL(vinfo1.majorno, 1); + BOOST_CHECK_EQUAL(vinfo1.minorno, 2); + BOOST_CHECK_EQUAL(vinfo1.patchno, 0); + BOOST_CHECK_EQUAL(vinfo1.devno, -1); + } + { + const extras::VersionInformation vinfo1 = extras::parse_version_information(""ecell4-test-1.2.dev4""); + BOOST_CHECK_EQUAL(vinfo1.header, ""ecell4-test-""); + BOOST_CHECK_EQUAL(vinfo1.majorno, 1); + BOOST_CHECK_EQUAL(vinfo1.minorno, 2); + BOOST_CHECK_EQUAL(vinfo1.patchno, 0); + BOOST_CHECK_EQUAL(vinfo1.devno, 4); + } + { + const extras::VersionInformation vinfo1 = extras::parse_version_information(""ecell4-test-1.2.3c4.dev5""); + BOOST_CHECK_EQUAL(vinfo1.header, ""ecell4-test-""); + BOOST_CHECK_EQUAL(vinfo1.majorno, 1); + BOOST_CHECK_EQUAL(vinfo1.minorno, 2); + BOOST_CHECK_EQUAL(vinfo1.patchno, 3); + BOOST_CHECK_EQUAL(vinfo1.pre, extras::VersionInformation::RC); + BOOST_CHECK_EQUAL(vinfo1.preno, 4); + BOOST_CHECK_EQUAL(vinfo1.devno, 5); + } + { + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.0"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.1"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-2.0.0"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-2.0.0b1"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-2.0.0b1"", ""ecell4-test-2.0.0b1"")); + BOOST_CHECK(!extras::check_version_information(""ecell4-test-1.0.1"", ""ecell4-test-2.0.0b1"")); + BOOST_CHECK(!extras::check_version_information(""ecell4-test-1.0"", ""ecell4-test-2.0.0b1"")); + BOOST_CHECK(!extras::check_version_information(""ecell4-test-1.0.dev1"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.1.dev1"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.0.dev1"", ""ecell4-test-1.0.dev1"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.0.dev2"", ""ecell4-test-1.0.dev1"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-2.0.0b1.dev1"", ""ecell4-test-1.0.dev1"")); + BOOST_CHECK(!extras::check_version_information(""ecell4-test-1.0a1"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.1a2"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.0rc1"", ""ecell4-test-1.0a5"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.0.1a1"", ""ecell4-test-1.0"")); + BOOST_CHECK(extras::check_version_information(""ecell4-test-1.0.1c1"", ""ecell4-test-1.0.1rc1"")); + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/Triangle_test.cpp",".cpp","5149","169","#define BOOST_TEST_MODULE ""Triangle_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include +#include + +using ecell4::Real; +using ecell4::Real3; +using ecell4::Triangle; + +BOOST_AUTO_TEST_CASE(Triangle_distance_test) +{ + constexpr std::size_t N = 100; + constexpr Real tol = 1e-8; + // test triangle + // + // y .' + // A | .' + // ----|' B + // 1|`. .' + // F | `. .' + // | G `. .' + // ----+------`----- x + // 0| 1| + // E | D | C + + std::mt19937 mt(123456789); + std::uniform_real_distribution uni(0.0, 1.0); + + ecell4::UnlimitedBoundary boundary; + + const Triangle tri(Real3(0, 0, 0), Real3(1, 0, 0), Real3(0, 1, 0)); + BOOST_TEST_MESSAGE(""triangle constructed""); + + // check region A + for(std::size_t i=0; i +#include +#include + +#include + +using namespace ecell4; + + +template +class RandomNumberGeneratorTest + : public CppUnit::TestFixture +{ +public: + + typedef Timpl_ implementation_type; + + CPPUNIT_TEST_SUITE(RandomNumberGeneratorTest); + CPPUNIT_TEST(test_seed); + CPPUNIT_TEST_SUITE_END(); + +public: + + void setUp() + { + target = new implementation_type(); + } + + void tearDown() + { + delete target; + } + + void test_seed(); + +private: + + RandomNumberGenerator *target; +}; + +CPPUNIT_TEST_SUITE_REGISTRATION( + RandomNumberGeneratorTest); + +template +void RandomNumberGeneratorTest::test_seed() +{ + target->seed(0); + // CPPUNIT_ASSERT_EQUAL(1, 2); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/ParticleSpace_test.cpp",".cpp","5641","151","#define BOOST_TEST_MODULE ""ParticleSpace_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include +#include + +using namespace ecell4; + +struct Fixture +{ + typedef ParticleSpaceCellListImpl particle_space_type; + + const Real3 edge_lengths; + const Integer3 matrix_sizes; + const Real radius; + + Fixture() : + edge_lengths(1, 1, 1), + matrix_sizes(5, 5, 5), + radius(0.005) + {} +}; + +BOOST_FIXTURE_TEST_SUITE(suite, Fixture) + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_constructor) +{ + std::unique_ptr space(new particle_space_type(edge_lengths, matrix_sizes)); + + BOOST_CHECK_EQUAL((*space).list_species().size(), 0); + BOOST_CHECK_EQUAL((*space).num_particles(), 0); + BOOST_CHECK_EQUAL((*space).edge_lengths(), edge_lengths); + BOOST_CHECK_EQUAL((*space).volume(), 1.0); + BOOST_CHECK_EQUAL((*space).t(), 0.0); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_update_remove) +{ + std::unique_ptr space(new particle_space_type(edge_lengths, matrix_sizes)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const Species sp1 = Species(""A""); + const Species sp2 = Species(""B""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.5, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); + + BOOST_CHECK(!(*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.25, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); + + BOOST_CHECK(!(*space).update_particle(pid1, Particle(sp2, edge_lengths * 0.1, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(), 1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 1); + + (*space).remove_particle(pid1); + BOOST_CHECK_EQUAL((*space).num_particles(), 0); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); + BOOST_CHECK_EQUAL((*space).num_particles(sp2), 0); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_remove) +{ + std::unique_ptr space(new particle_space_type(edge_lengths, matrix_sizes)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const ParticleID pid2 = pidgen(); + const ParticleID pid3 = pidgen(); + const Species sp1 = Species(""A""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, edge_lengths * 0.5, radius, 0))); + BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, edge_lengths * 0.25, radius, 0))); + BOOST_CHECK((*space).update_particle(pid3, Particle(sp1, edge_lengths * 0.75, radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 3); + + (*space).remove_particle(pid2); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); + (*space).remove_particle(pid3); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + (*space).remove_particle(pid1); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 0); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_exception) +{ + std::unique_ptr space(new particle_space_type(edge_lengths, matrix_sizes)); + SerialIDGenerator pidgen; + const ParticleID pid1 = pidgen(); + + BOOST_CHECK_THROW((*space).remove_particle(pid1), NotFound); +} + +BOOST_AUTO_TEST_CASE(ParticleSpace_test_list_particles_within_radius) +{ + std::unique_ptr space(new particle_space_type(edge_lengths, matrix_sizes)); + SerialIDGenerator pidgen; + + const ParticleID pid1 = pidgen(); + const ParticleID pid2 = pidgen(); + const Species sp1 = Species(""A""); + + BOOST_CHECK((*space).update_particle(pid1, Particle(sp1, Real3(0.5, 0.5, 0.5), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 1); + + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid1); + BOOST_CHECK_CLOSE(retval[0].second, 0.009 - radius, 1e-6); + } + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius, pid1).size(), 0); + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.511, 0.5, 0.5), radius).size(), 0); + + BOOST_CHECK((*space).update_particle(pid2, Particle(sp1, Real3(0.511, 0.5, 0.5), radius, 0))); + BOOST_CHECK_EQUAL((*space).num_particles(sp1), 2); + + BOOST_CHECK_EQUAL((*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius).size(), 2); + (*space).remove_particle(pid1); + { + const std::vector, Real> > + retval = (*space).list_particles_within_radius(Real3(0.509, 0.5, 0.5), radius); + BOOST_CHECK_EQUAL(retval.size(), 1); + BOOST_CHECK_EQUAL(retval[0].first.first, pid2); + BOOST_CHECK_CLOSE(retval[0].second, 0.002 - radius, 1e-6); + } +} + +BOOST_AUTO_TEST_CASE(ParticleSpaceCellListImpl_test_constructor) +{ + std::unique_ptr space(new ParticleSpaceCellListImpl(edge_lengths, matrix_sizes)); + + BOOST_CHECK_EQUAL((*space).matrix_sizes(), matrix_sizes); +} + +BOOST_AUTO_TEST_SUITE_END() +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/ObjectIDContainer_test.cpp",".cpp","1484","56","#define BOOST_TEST_MODULE ""ObjectIDContainer_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include +#include +#include + +constexpr std::size_t N = 1000; + +BOOST_AUTO_TEST_CASE(ObjectIDContainer_add_update_remove) +{ + using namespace ecell4; + ObjectIDContainer container; + SerialIDGenerator idgen; + + std::vector ids; + for(std::size_t i=0; i +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include +#include + +using namespace ecell4; + + +BOOST_AUTO_TEST_CASE(Species_test_constructor) +{ + Species sp1(""A""); + Species sp2(""A( )""); +// Species sp2(""A( a , b ^ 1, c)""); + Species sp3(""A(a,b^1,c=p).B(a,b=u^1)""); +} + +BOOST_AUTO_TEST_CASE(Species_test_name) +{ + Species sp1(""test""); + BOOST_CHECK_EQUAL(sp1.serial(), ""test""); + Species sp2(""test()""); + BOOST_CHECK_EQUAL(sp2.serial(), ""test()""); + // BOOST_CHECK_EQUAL(sp2.serial(), ""test""); +} + +BOOST_AUTO_TEST_CASE(Species_test_attributes) +{ + Species sp(""test""); + + const std::string val1 = ""foo""; + const Real val2 = 1.5; + const Integer val3 = 3; + const bool val4 = true; + + sp.set_attribute(""attr1"", val1); + sp.set_attribute(""attr2"", val2); + sp.set_attribute(""attr3"", val3); + sp.set_attribute(""attr4"", val4); + sp.set_attribute(""attr5"", ""bar""); + + BOOST_ASSERT(sp.has_attribute(""attr1"")); + BOOST_ASSERT(sp.has_attribute(""attr2"")); + BOOST_ASSERT(sp.has_attribute(""attr3"")); + BOOST_ASSERT(sp.has_attribute(""attr4"")); + BOOST_ASSERT(sp.has_attribute(""attr5"")); + BOOST_ASSERT(!sp.has_attribute(""atrt1"")); + + const Species::attribute_type attr1 = sp.get_attribute(""attr1""); + const Species::attribute_type attr2 = sp.get_attribute(""attr2""); + const Species::attribute_type attr3 = sp.get_attribute(""attr3""); + const Species::attribute_type attr4 = sp.get_attribute(""attr4""); + const Species::attribute_type attr5 = sp.get_attribute(""attr5""); + + BOOST_ASSERT(attr1.type() == typeid(std::string)); + BOOST_ASSERT(attr2.type() == typeid(Quantity)); + BOOST_ASSERT(attr3.type() == typeid(Quantity)); + BOOST_ASSERT(attr4.type() == typeid(bool)); + BOOST_ASSERT(attr5.type() == typeid(std::string)); + + BOOST_CHECK_EQUAL(boost::get(attr1), val1); + BOOST_CHECK_EQUAL(boost::get >(attr2).magnitude, val2); + BOOST_CHECK_EQUAL(boost::get >(attr3).magnitude, val3); + BOOST_CHECK_EQUAL(boost::get(attr4), val4); + BOOST_CHECK_EQUAL(boost::get(attr5), ""bar""); + + BOOST_CHECK_EQUAL(sp.get_attribute_as(""attr1""), val1); + BOOST_CHECK_EQUAL(sp.get_attribute_as(""attr2""), val2); + BOOST_CHECK_EQUAL(sp.get_attribute_as(""attr3""), val3); + BOOST_CHECK_EQUAL(sp.get_attribute_as(""attr4""), val4); + BOOST_CHECK_EQUAL(sp.get_attribute_as(""attr5""), ""bar""); + + sp.remove_attribute(""attr1""); + sp.remove_attribute(""attr2""); + sp.remove_attribute(""attr3""); + sp.remove_attribute(""attr4""); + sp.remove_attribute(""attr5""); + + BOOST_ASSERT(!sp.has_attribute(""attr1"")); + BOOST_ASSERT(!sp.has_attribute(""attr2"")); + BOOST_ASSERT(!sp.has_attribute(""attr3"")); + BOOST_ASSERT(!sp.has_attribute(""attr4"")); + BOOST_ASSERT(!sp.has_attribute(""attr5"")); + + // Species species(""test""); + // species.set_attribute(""attr1"", ""value1""); + // species.set_attribute(""attr2"", ""value2""); + // BOOST_CHECK_EQUAL(species.get_attribute_as(""attr1""), ""value1""); + // BOOST_CHECK_EQUAL(species.get_attribute_as(""attr2""), ""value2""); + // species.remove_attribute(""attr1""); +} + +BOOST_AUTO_TEST_CASE(Species_test_match1) +{ + Species sp1, sp2; + + sp1.add_unit(UnitSpecies(""C"")); + sp1.add_unit(UnitSpecies(""A"")); + sp1.add_unit(UnitSpecies(""B"")); + BOOST_CHECK_EQUAL(sp1.serial(), ""C.A.B""); + + sp2.add_unit(UnitSpecies(""A"")); + sp2.add_unit(UnitSpecies(""C"")); + BOOST_CHECK_EQUAL(sp2.serial(), ""A.C""); + + // BOOST_CHECK(sp2.match(sp1)); + // BOOST_CHECK(!sp1.match(sp2)); +} + +BOOST_AUTO_TEST_CASE(Species_test_match2) +{ + Species sp1, sp2; + + sp1.add_unit(UnitSpecies(""B"")); + sp1.add_unit(UnitSpecies(""A"")); + sp1.add_unit(UnitSpecies(""A"")); + BOOST_CHECK_EQUAL(sp1.serial(), ""B.A.A""); + + sp2.add_unit(UnitSpecies(""B"")); + sp2.add_unit(UnitSpecies(""A"")); + BOOST_CHECK_EQUAL(sp2.serial(), ""B.A""); + + // BOOST_CHECK(sp2.match(sp1)); + // BOOST_CHECK(!sp1.match(sp2)); +} + +BOOST_AUTO_TEST_CASE(Species_test_serialization) +{ + Species sp1(""X(a^1).Y(a^3,b).X(a^2).Y(a^1,b^2).X(a^3)""); + + BOOST_CHECK_EQUAL( + format_species(Species(""X(a^1).Y(a^3,b).X(a^2).Y(a^1,b^2).X(a^3)"")).serial(), + ""X(a^1).Y(a^1,b).X(a^2).Y(a^2,b^3).X(a^3)""); + BOOST_CHECK_EQUAL( + format_species(Species(""X(a^1).Y(a^3,b^4).X(a^3).Z(a^4,b^5).Y(a^1,b^2).Z(a^2,b^5)"")).serial(), + ""X(a^1).Y(a^1,b^2).Z(a^2,b^3).Z(a^4,b^3).Y(a^5,b^4).X(a^5)""); + BOOST_CHECK_EQUAL( + format_species(Species(""X(a^3,b^1).X(a^2,b).X(a,b^3).X(a^1,b^4).X(a^4,b^2)"")).serial(), + ""X(a,b^1).X(a^1,b^2).X(a^2,b^3).X(a^3,b^4).X(a^4,b)""); +} + +BOOST_AUTO_TEST_CASE(Species_test_match3) +{ + BOOST_CHECK_EQUAL(SpeciesExpressionMatcher(Species(""A"")).count(Species(""A.A.A"")), 3); + + BOOST_CHECK_EQUAL(SpeciesExpressionMatcher(Species(""_1._2"")).count(Species(""A.B.C"")), 6); + + // MatchObject::context_type::variable_container_type globals; + // globals[""_1""] = ""A""; + // BOOST_CHECK_EQUAL( + // SpeciesExpressionMatcher((Species(""_1._2"")).count(Species(""A.B.C""), globals), 2); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/LatticeSpace_test.cpp",".cpp","22256","651","#define BOOST_TEST_MODULE ""LatticeSpace_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +#include +#else +#define BOOST_TEST_NO_LIB +#include +#endif + +#include + +#include +#include +#include +#include + +using namespace ecell4; + +struct Fixture +{ + const Real3 edge_lengths; + const Real voxel_radius; + LatticeSpaceVectorImpl space; + SerialIDGenerator sidgen; + const Real D, radius; + const Species sp; + Fixture() + : edge_lengths(2.5e-8, 2.5e-8, 2.5e-8), voxel_radius(2.5e-9), + space(edge_lengths, voxel_radius, false), sidgen(), D(1e-12), + radius(2.5e-9), sp(""A"", 2.5e-9, 1e-12) + { + space.make_molecular_type(sp, """"); + } +}; + +BOOST_FIXTURE_TEST_SUITE(suite, Fixture) + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_constructor) { ; } + +BOOST_AUTO_TEST_CASE(CheckVacantSize) +{ + BOOST_CHECK_EQUAL(space.actual_size(), space.vacant()->size()); + BOOST_CHECK_EQUAL(space.num_voxels_exact(Species("""")), + space.vacant()->size()); +} + +BOOST_AUTO_TEST_CASE(GetVoxel) +{ + const Real3 position(1.25e-8, 1.25e-8, 1.25e-8); + const Integer coordinate(space.position2coordinate(position)); + + { + const auto view(space.get_voxel_at(coordinate)); + BOOST_CHECK_EQUAL(view.pid, ParticleID()); + BOOST_CHECK_EQUAL(view.species, space.vacant()->species()); + } + + ParticleID id(sidgen()); + BOOST_CHECK(space.update_voxel(id, sp, coordinate)); + + { + const auto view(space.get_voxel_at(coordinate)); + BOOST_CHECK_EQUAL(view.pid, id); + BOOST_CHECK_EQUAL(view.species, sp); + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_has_species) +{ + BOOST_CHECK(!space.has_species(sp)); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_update_particle) +{ + ParticleID id(sidgen()); + + Real3 pos(2e-8, 1.7e-8, 1.5e-8); + Real r(1.0); + // Real d(2.3); + // Particle particle(sp, pos, r, d); + + // BOOST_CHECK(space.update_particle(id, particle)); + BOOST_CHECK(space.update_voxel(id, sp, space.position2coordinate(pos))); + BOOST_CHECK(space.has_species(sp)); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_num_voxels) +{ + ParticleID id(sidgen()); + Real3 pos(2e-8, 1.7e-8, 1.5e-8); + Real r(1.0); + // Real d(2.3); + // Particle particle(sp, pos, r, d); + + ParticleID a_id(sidgen()); + Species a(std::string(""ANOTHER"")); + Real3 pos1(1e-8, 2e-8, 1e-9); + Real r1(1.1); + Real d1(4.3); + BOOST_CHECK(space.make_molecular_type(a, """")); + // Particle another(a, pos1, r1, d1); + + BOOST_CHECK(space.update_voxel(id, sp, space.position2coordinate(pos))); + BOOST_CHECK(space.update_voxel(a_id, a, space.position2coordinate(pos1))); + // BOOST_CHECK(space.update_particle(id, particle)); + // BOOST_CHECK(space.update_particle(a_id, another)); + BOOST_CHECK_EQUAL(space.num_voxels(sp), 1); + BOOST_CHECK_EQUAL(space.num_voxels(), 2); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_list_voxels) +{ + ParticleID id(sidgen()); + Real3 pos(2e-8, 1.7e-8, 1.5e-8); + Real r(1.0); + // Real d(2.3); + // Particle particle(sp, pos, r, d); + + ParticleID a_id(sidgen()); + Species a(std::string(""ANOTHER"")); + Real3 pos1(1e-8, 2e-8, 1e-9); + Real r1(1.1); + Real d1(4.3); + BOOST_CHECK(space.make_molecular_type(a, """")); + // Particle another(a, pos1, r1, d1); + + BOOST_CHECK(space.update_voxel(id, sp, space.position2coordinate(pos))); + BOOST_CHECK(space.update_voxel(a_id, a, space.position2coordinate(pos1))); + // BOOST_CHECK(space.update_particle(id, particle)); + // BOOST_CHECK(space.update_particle(a_id, another)); + + const auto test_list(space.list_voxels(sp)); + const auto list(space.list_voxels()); + BOOST_CHECK_EQUAL(list.size(), 2); + BOOST_CHECK_EQUAL(test_list.size(), 1); +} + +// BOOST_AUTO_TEST_CASE(LatticeSpace_test_register_species) +// { +// BOOST_CHECK(space.register_species(sp)); +// BOOST_CHECK(space.has_species(sp)); +// +// std::vector list; +// list.push_back(sp); +// +// BOOST_CHECK(list == space.list_species()); +// } + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_coordinate_global_translation) +{ + for (Integer coord(0); coord < space.size(); ++coord) + { + const Integer3 global(space.coordinate2global(coord)); + VoxelSpaceBase::coordinate_type created_coord( + space.global2coordinate(global)); + BOOST_CHECK_EQUAL(coord, created_coord); + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_coordinate_position_translation) +{ + const Real3 origin_pos(space.coordinate2position(0)); + BOOST_ASSERT(origin_pos[0] < 0); + BOOST_ASSERT(origin_pos[1] < 0); + BOOST_ASSERT(origin_pos[2] < 0); + + const VoxelSpaceBase::coordinate_type origin( + (space.col_size() + 3) * (space.row_size() + 2) + 1); + const Real3 origin_p(space.coordinate2position(origin)); + BOOST_ASSERT(origin_p[0] == 0); + BOOST_ASSERT(origin_p[1] == 0); + BOOST_ASSERT(origin_p[2] == 0); + + BOOST_ASSERT(space.num_neighbors(origin) == 12); + for (Integer i(0); i < 12; ++i) + { + const Real3 neighbor( + space.coordinate2position(space.get_neighbor(origin, i))); + BOOST_CHECK(origin_p != neighbor); + const VoxelSpaceBase::coordinate_type coord( + space.position2coordinate(origin_p * 0.7 + neighbor * 0.3)); + BOOST_CHECK_EQUAL(origin, coord); + } + + Integer size((space.col_size() + 2) * (space.layer_size() + 2) * + (space.row_size() + 2)); + for (VoxelSpaceBase::coordinate_type coord(0); coord < size; ++coord) + { + const Real3 pos(space.coordinate2position(coord)); + // const Integer3 global(space.position2global(pos)); + const VoxelSpaceBase::coordinate_type created_coord( + space.position2coordinate(pos)); + BOOST_CHECK_EQUAL(coord, created_coord); + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_add_remove_molecule) +{ + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(3, 4, 5))); + ParticleID pid(sidgen()); + BOOST_CHECK(space.update_voxel(pid, sp, coord)); + BOOST_CHECK_EQUAL(space.num_voxels(sp), 1); + + std::shared_ptr mt(space.get_voxel_pool_at(coord)); + BOOST_CHECK(!mt->is_vacant()); + + BOOST_CHECK(space.remove_voxel(coord)); + std::shared_ptr vacant(space.get_voxel_pool_at(coord)); + BOOST_CHECK(vacant->is_vacant()); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_move) +{ + const Integer3 global0(2, 3, 4); + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(global0)); + + ParticleID pid(sidgen()); + BOOST_CHECK(space.update_voxel(pid, sp, coord)); + + std::shared_ptr from_mt(space.get_voxel_pool_at(coord)); + BOOST_CHECK(!from_mt->is_vacant()); + + const Integer3 global1(2, 4, 4); + const VoxelSpaceBase::coordinate_type to_coord( + space.global2coordinate(global1)); + + BOOST_CHECK(space.move(coord, to_coord)); + + std::shared_ptr mt(space.get_voxel_pool_at(to_coord)); + BOOST_CHECK(!mt->is_vacant()); + + BOOST_CHECK(space.update_voxel(sidgen(), sp, coord)); + BOOST_CHECK(!space.move(coord, to_coord)); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_update_molecule) +{ + Species reactant(std::string(""Reactant"")), product(std::string(""Product"")); + + const Integer3 global(3, 4, 5); + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(global)); + + BOOST_CHECK(space.make_molecular_type(reactant, """")); + BOOST_CHECK(space.make_molecular_type(product, """")); + + ParticleID pid(sidgen()); + BOOST_CHECK(space.update_voxel(pid, reactant, coord)); + // space.update_voxel( + // ParticleVoxel(product, coord, radius, D)); + BOOST_CHECK(space.remove_voxel(coord)); + BOOST_CHECK(space.update_voxel(pid, product, coord)); + + std::shared_ptr mt(space.get_voxel_pool_at(coord)); + BOOST_ASSERT(mt->species() == product); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_update_voxel) +{ + const ParticleID pid(sidgen()); + for (VoxelSpaceBase::coordinate_type coord(0); coord < space.size(); + ++coord) + { + if (!space.is_inside(coord)) + { + continue; + } + + const Real3 pos(space.coordinate2position(coord)); + space.update_voxel(pid, sp, coord); + BOOST_CHECK_EQUAL(space.num_voxels(), 1); + + const auto view(space.list_voxels()[0]); + BOOST_CHECK_EQUAL(pid, view.pid); + BOOST_CHECK_EQUAL(coord, view.voxel); + // BOOST_CHECK_EQUAL(sp, view.species); + //[TODO] Species is not comparable. + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_lattice_structure) +{ + for (VoxelSpaceBase::coordinate_type coord(0); coord < space.size(); + ++coord) + { + if (space.is_inside(coord)) + { + ParticleID pid(sidgen()); + BOOST_CHECK(space.update_voxel(pid, sp, coord)); + } + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_neighbor) +{ + for (VoxelSpaceBase::coordinate_type coord(0); coord < space.size(); + ++coord) + { + if (!space.is_inside(coord)) + { + continue; + } + + BOOST_ASSERT(space.num_neighbors(coord) == 12); + const Real3 center(space.coordinate2position(coord)); + for (int i(0); i < 12; ++i) + { + VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, i)); + if (!space.is_inside(neighbor)) + { + continue; + } + + Real3 pos(space.coordinate2position(neighbor)); + // Real3 vec((pos-center)/voxel_radius/2); + Real r_ratio(length(pos - center) / voxel_radius / 2); + BOOST_ASSERT(r_ratio < 1.0001); + } + } +} + +BOOST_AUTO_TEST_SUITE_END() + +struct PeriodicFixture +{ + const Real3 edge_lengths; + const Real voxel_radius; + LatticeSpaceVectorImpl space; + SerialIDGenerator sidgen; + const Real D, radius; + const Species sp; + PeriodicFixture() + : edge_lengths(2.5e-8, 2.5e-8, 2.5e-8), voxel_radius(2.5e-9), + space(edge_lengths, voxel_radius, true), sidgen(), D(1e-12), + radius(2.5e-9), sp(std::string(""A""), 2.5e-9, 1e-12) + { + space.make_molecular_type(sp, """"); + } +}; + +BOOST_FIXTURE_TEST_SUITE(periodic_suite, PeriodicFixture) + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_periodic_col) +{ + std::cerr << "" < periodic_col > ""; + const int col_size(space.col_size()), row_size(space.row_size()), + layer_size(space.layer_size()); + for (int i(0); i < row_size; ++i) + for (int j(0); j < layer_size; ++j) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(0, i, j))); + + BOOST_CHECK(space.update_voxel(sidgen(), sp, coord)); + } + + // from 0 to col_size-1 + for (int i(0); i < row_size; ++i) + for (int j(0); j < layer_size; ++j) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(0, i, j))); + + const Integer nrnd((j & 1) == 1 ? 2 : 3); + const VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, nrnd)); + + BOOST_CHECK_EQUAL(space.coordinate2global(neighbor).col, + col_size - 1); + BOOST_CHECK(space.move(coord, neighbor)); + } + + // from col_size-1 to 0 + for (int i(0); i < row_size; ++i) + for (int j(0); j < layer_size; ++j) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col_size - 1, i, j))); + + const Integer nrnd((j & 1) == 1 ? 4 : 5); + const VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, nrnd)); + + BOOST_CHECK_EQUAL(space.coordinate2global(neighbor).col, 0); + BOOST_CHECK(space.move(coord, neighbor)); + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_periodic_row) +{ + const int col_size(space.col_size()), row_size(space.row_size()), + layer_size(space.layer_size()); + for (int layer(0); layer < layer_size; ++layer) + for (int col(0); col < col_size; ++col) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col, 0, layer))); + + BOOST_CHECK(space.update_voxel(sidgen(), sp, coord)); + } + + // from 0 to row_size-1 + for (int layer(0); layer < layer_size; ++layer) + for (int col(0); col < col_size; ++col) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col, 0, layer))); + + const Integer nrnd(0); + const VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, nrnd)); + + BOOST_CHECK_EQUAL(space.coordinate2global(neighbor).row, + row_size - 1); + BOOST_CHECK(space.move(coord, neighbor)); + } + // from row_size-1 to 0 + for (int layer(0); layer < layer_size; ++layer) + for (int col(0); col < col_size; ++col) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col, row_size - 1, layer))); + const Integer nrnd(1); + const VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, nrnd)); + + BOOST_CHECK_EQUAL(space.coordinate2global(neighbor).row, 0); + BOOST_CHECK(space.move(coord, neighbor)); + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_periodic_layer) +{ + const int col_size(space.col_size()), row_size(space.row_size()), + layer_size(space.layer_size()); + + for (int row(0); row < row_size; ++row) + for (int col(0); col < col_size; ++col) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col, row, 0))); + + BOOST_CHECK(space.update_voxel(sidgen(), sp, coord)); + } + + // from 0 to layer_size-1 + for (int row(0); row < row_size; ++row) + for (int col(0); col < col_size; ++col) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col, row, 0))); + + const Integer nrnd((col & 1) == 1 ? 8 : 9); + const VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, nrnd)); + + BOOST_CHECK_EQUAL(space.coordinate2global(neighbor).layer, + layer_size - 1); + BOOST_CHECK(space.move(coord, neighbor)); + } + + // from layer_size-1 to 0 + for (int row(0); row < row_size; ++row) + for (int col(0); col < col_size; ++col) + { + const VoxelSpaceBase::coordinate_type coord( + space.global2coordinate(Integer3(col, row, layer_size - 1))); + const Integer nrnd((col & 1) == 1 ? 10 : 11); + const VoxelSpaceBase::coordinate_type neighbor( + space.get_neighbor(coord, nrnd)); + + BOOST_CHECK_EQUAL(space.coordinate2global(neighbor).layer, 0); + BOOST_CHECK(space.move(coord, neighbor)); + } +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_coordinates2) +{ + const Integer3 g1(4, 4, 4); + const VoxelSpaceBase::coordinate_type pc1(space.global2coordinate(g1)); + const Integer3 g3(space.coordinate2global(pc1)); + + BOOST_CHECK(g1.col == g3.col && g1.row == g3.row && g1.layer == g3.layer); + + const Real3 p1(space.global2position(g1)); + const Integer3 g4(space.position2global(p1)); + + BOOST_CHECK(g1.col == g4.col && g1.row == g4.row && g1.layer == g4.layer); + BOOST_CHECK_EQUAL(pc1, space.position2coordinate(p1)); + + const Real3 p2(space.coordinate2position(pc1)); + BOOST_CHECK_EQUAL(pc1, space.position2coordinate(p2)); +} + +BOOST_AUTO_TEST_SUITE_END() + +struct StructureFixture +{ + const Real3 edge_lengths; + const Real voxel_radius; + LatticeSpaceVectorImpl space; + SerialIDGenerator sidgen; + const Real D, radius; + const Species structure, sp; + StructureFixture() + : edge_lengths(2.5e-8, 2.5e-8, 2.5e-8), voxel_radius(2.5e-9), + space(edge_lengths, voxel_radius, false), sidgen(), D(1e-12), + radius(2.5e-9), structure(""Structure"", 2.5e-9, 0), + sp(""A"", 2.5e-9, 1e-12, ""Structure"") + { + space.make_structure_type(structure, """"); + space.make_molecular_type(sp, structure.serial()); + } +}; + +BOOST_FIXTURE_TEST_SUITE(structure_suite, StructureFixture) + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_structure_update) +{ + const Real3 pos(2.7e-9, 1.3e-8, 2.0e-8); + BOOST_CHECK(space.update_structure(Particle(structure, pos, radius, D))); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 1); + ParticleID pid(sidgen()); + // XXX: Particle has no information about the location. + // XXX: BOOST_CHECK(space.update_particle(pid, Particle(sp, pos, radius, + // D))); + BOOST_CHECK(space.update_voxel(pid, sp, space.position2coordinate(pos))); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels(sp).size(), 1); + BOOST_CHECK(space.remove_voxel(pid)); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 1); // TODO -> 0 + BOOST_CHECK_EQUAL(space.list_voxels(sp).size(), 0); + + Species sp2(""B"", 2.5e-9, 1e-12); + BOOST_CHECK(space.make_molecular_type(sp2, """")); + BOOST_CHECK_THROW( + space.update_voxel(sidgen(), sp2, space.position2coordinate(pos)), + NotSupported); + // BOOST_CHECK_THROW( + // space.update_particle(sidgen(), Particle(sp2, pos, radius, D)), + // NotSupported); +} + +BOOST_AUTO_TEST_CASE(LatticeSpace_test_structure_move) +{ + const Real3 pos1(2.7e-9, 1.3e-8, 2.0e-8); + const Real3 pos2(1.2e-8, 1.5e-8, 1.8e-8); + BOOST_CHECK(space.update_structure(Particle(structure, pos1, radius, D))); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 1); + BOOST_CHECK(space.update_structure(Particle(structure, pos2, radius, D))); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 2); // TODO -> 0 + BOOST_CHECK_EQUAL(space.list_voxels().size(), 2); // TODO -> 0 + + ParticleID pid(sidgen()); + // XXX: BOOST_CHECK(space.update_particle(pid, Particle(sp, pos1, radius, + // D))); + BOOST_CHECK(space.update_voxel(pid, sp, space.position2coordinate(pos1))); + BOOST_CHECK_EQUAL(space.list_voxels(sp).size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels(structure).size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 2); // TODO -> 1 + const VoxelSpaceBase::coordinate_type coord1( + space.position2coordinate(pos1)), + coord2(space.position2coordinate(pos2)); + BOOST_CHECK(space.move(coord1, coord2)); + BOOST_CHECK_EQUAL(space.list_voxels(sp).size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels(structure).size(), 1); + BOOST_CHECK_EQUAL(space.list_voxels().size(), 2); // TODO -> 1 +} + +#ifdef WITH_HDF5 +BOOST_AUTO_TEST_CASE(LatticeSpace_test_save_and_load) +{ + + space.make_structure_type(structure, """"); + const Integer l(space.layer_size() / 2); + for (int c(0); c < space.col_size(); ++c) + for (int r(0); r < space.row_size(); ++r) + { + const Real3 pos(space.global2position(Integer3(c, r, l))); + BOOST_ASSERT( + space.update_structure(Particle(structure, pos, radius, D))); + } + + const VoxelSpaceBase::coordinate_type center(space.global2coordinate( + Integer3(space.col_size() / 2, space.row_size() / 2, l))), + point(space.global2coordinate( + Integer3(space.col_size() / 2, space.row_size() / 2, l - 2))); + BOOST_ASSERT(space.update_voxel(sidgen(), sp, center)); + // #XXX !!!Warning!!! Ideally, not necessary to give structure.serial() + // explicitly + BOOST_ASSERT( + space.update_voxel(sidgen(), Species(""B"", 2.5e-9, 1e-12), point)); + + H5::H5File fout(""data.h5"", H5F_ACC_TRUNC); + std::unique_ptr group( + new H5::Group(fout.createGroup(""VoxelSpaceBase""))); + space.save_hdf5(group.get()); + fout.close(); + + LatticeSpaceVectorImpl space2(Real3(3e-8, 3e-8, 3e-8), voxel_radius); + H5::H5File fin(""data.h5"", H5F_ACC_RDONLY); + const H5::Group groupin(fin.openGroup(""VoxelSpaceBase"")); + space2.load_hdf5(groupin); + fin.close(); + + BOOST_CHECK_EQUAL(space.edge_lengths(), space2.edge_lengths()); + BOOST_CHECK_EQUAL(space.voxel_radius(), space2.voxel_radius()); + BOOST_CHECK_EQUAL(space.is_periodic(), space2.is_periodic()); + BOOST_CHECK_EQUAL(space.t(), space2.t()); + BOOST_CHECK_EQUAL(space.num_voxels(), space2.num_voxels()); + + std::vector species(space.list_species()); + for (std::vector::const_iterator itr(species.begin()); + itr != species.end(); ++itr) + { + const Species species((*itr).serial()); + + std::shared_ptr vp1(space.find_voxel_pool(species)); + std::shared_ptr vp2(space2.find_voxel_pool(species)); + + const MoleculePool *mtb1(dynamic_cast(vp1.get())); + const MoleculePool *mtb2(dynamic_cast(vp2.get())); + BOOST_ASSERT((mtb1 && mtb2) || (!mtb1 && !mtb2)); + + if (!mtb1 || !mtb2) + { + continue; + } + + MoleculePool::container_type voxels1, voxels2; + std::copy(mtb1->begin(), mtb1->end(), back_inserter(voxels1)); + std::copy(mtb2->begin(), mtb2->end(), back_inserter(voxels2)); + BOOST_ASSERT(voxels1.size() == voxels2.size()); + std::sort(voxels1.begin(), voxels1.end()); + std::sort(voxels2.begin(), voxels2.end()); + for (MoleculePool::container_type::size_type i(0); i < voxels1.size(); + ++i) + { + BOOST_CHECK_EQUAL(voxels1.at(i).pid, voxels2.at(i).pid); + BOOST_CHECK_EQUAL(voxels1.at(i).coordinate, + voxels2.at(i).coordinate); + } + } +} +#endif + +BOOST_AUTO_TEST_SUITE_END() +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/Barycentric_test.cpp",".cpp","2767","101","#define BOOST_TEST_MODULE ""Barycentric_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include + +using namespace ecell4; + +static const Real tolerance = 1.e-10; +static const std::size_t N = 10000; + +BOOST_AUTO_TEST_CASE(Barycentric_test_operator) +{ + const Barycentric b1(1., 2., 3.); + const Barycentric b2(6., 4., 5.); + const Barycentric b3 = b1 + b2; + + BOOST_CHECK_CLOSE_FRACTION(b3[0], 7.0, tolerance); + BOOST_CHECK_CLOSE_FRACTION(b3[1], 6.0, tolerance); + BOOST_CHECK_CLOSE_FRACTION(b3[2], 8.0, tolerance); + + const Barycentric b4 = b2 - b1; + + BOOST_CHECK_CLOSE_FRACTION(b4[0], 5.0, tolerance); + BOOST_CHECK_CLOSE_FRACTION(b4[1], 2.0, tolerance); + BOOST_CHECK_CLOSE_FRACTION(b4[2], 2.0, tolerance); +} + + +BOOST_AUTO_TEST_CASE(Barycentric_test_is_inside) +{ + const Barycentric b1(1., 0., 0.); + const Barycentric b2(0.2, 0.3, 0.5); + + BOOST_CHECK(is_inside(b1)); + BOOST_CHECK(is_inside(b2)); + + const Barycentric b3(0., 0., 0.); + const Barycentric b4(1., 2., 3.); + const Barycentric b5(1., 1., -1.); + + BOOST_CHECK(!is_inside(b3)); + BOOST_CHECK(!is_inside(b4)); + BOOST_CHECK(!is_inside(b5)); +} + +BOOST_AUTO_TEST_CASE(Barycentric_test_on_plane) +{ + const Barycentric b1(1., 0., 0.); + const Barycentric b2(0.2, 0.3, 0.5); + const Barycentric b3(1., 1., -1.); + + BOOST_CHECK(on_plane(b1)); + BOOST_CHECK(on_plane(b2)); + BOOST_CHECK(on_plane(b3)); + + const Barycentric b4(0., 0., 0.); + const Barycentric b5(1., 2., 3.); + + BOOST_CHECK(!on_plane(b4)); + BOOST_CHECK(!on_plane(b5)); +} + +BOOST_AUTO_TEST_CASE(Barycentric_test_transformation) +{ + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + for(std::size_t i=0; iuniform(0., 1.); + const Real b = rng->uniform(0., 1. - a); + const Real c = 1. - a - b; + const Barycentric bary(a, b, c); + + const Real3 v0(0., 0., 0.); + const Real3 v1 = rng->direction3d(1.); + Real3 v2; + while(true) + { + v2 = rng->direction3d(1.); + const Real dot = std::abs(dot_product(v1, v2)); + if(std::abs(dot - 1.0) > tolerance) break; + } + const Triangle tri(v0, v1, v2); + + const Real3 absolute = to_absolute(bary, tri); + const Barycentric ret = to_barycentric(absolute, tri); + + BOOST_CHECK_CLOSE_FRACTION(bary[0], ret[0], tolerance); + BOOST_CHECK_CLOSE_FRACTION(bary[1], ret[1], tolerance); + BOOST_CHECK_CLOSE_FRACTION(bary[2], ret[2], tolerance); + } +} + +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/geometry_test.cpp",".cpp","1544","54","#define BOOST_TEST_MODULE ""geometry_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include + +using namespace ecell4; + +static const Real tolerance = 1.e-10; +static const std::size_t N = 10000; + +BOOST_AUTO_TEST_CASE(geometry_test_rotate) +{ + std::shared_ptr rng(new GSLRandomNumberGenerator()); + const Real3 unitx(1, 0, 0); + const Real3 unity(0, 1, 0); + const Real3 unitz(0, 0, 1); + + for(std::size_t i=0; iuniform(-M_PI, M_PI); + const Real3 result = rotate(angle, unitz, unitx); + + BOOST_CHECK_CLOSE_FRACTION(result[0], std::cos(angle), tolerance); + BOOST_CHECK_CLOSE_FRACTION(result[1], std::sin(angle), tolerance); + BOOST_CHECK_SMALL(result[2], tolerance); + } +} + +BOOST_AUTO_TEST_CASE(geometry_test_angle) +{ + std::shared_ptr rng(new GSLRandomNumberGenerator()); + const Real3 unitz(0, 0, 1); + const Real3 unitx(1, 0, 0); + + for(std::size_t i=0; iuniform(-M_PI, M_PI); + const Real a = rng->uniform(0, 2); + const Real b = rng->uniform(0, 2); + const Real3 rotated = rotate(angle, unitz, unitx); + const Real result = angle(unitx * a, rotated * b); + + BOOST_CHECK_CLOSE_FRACTION(result, angle, tolerance); + } +} + +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/PeriodicRTree_test.cpp",".cpp","10527","317","#define BOOST_TEST_MODULE ""PeriodicRTree_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + + +#include + +// Some of the CI environments uses relatively old version of Boost. +// std::tuple can be used with Boost 1.68.0+. +#include + +#include +#include +#include +#include +#include +#include + +using namespace ecell4; + +struct AlwaysTightAABBGetter +{ + AABB operator()(const Particle& p, const Real) const noexcept + { + const Real3 radius(p.radius(), p.radius(), p.radius()); + return AABB(p.position() - radius, p.position() + radius); + } +}; + +struct FixedMarginAABBGetter +{ + AABB operator()(const Particle& p, const Real margin) const noexcept + { + const Real3 radius(p.radius() + margin, + p.radius() + margin, + p.radius() + margin); + return AABB(p.position() - radius, p.position() + radius); + } +}; + +struct ScaledMarginAABBGetter +{ + AABB operator()(const Particle& p, const Real margin) const noexcept + { + const Real3 radius(p.radius() + p.D() * margin, + p.radius() + p.D() * margin, + p.radius() + p.D() * margin); + return AABB(p.position() - radius, p.position() + radius); + } +}; + +// Some of the CI environments uses relatively old version of Boost. +// std::tuple can be used with Boost 1.68.0+. +using aabb_getters = boost::mpl::list< + AlwaysTightAABBGetter, FixedMarginAABBGetter, ScaledMarginAABBGetter>; + +struct Query +{ + ParticleID ignore; + Real3 center; + Real radius; + + boost::optional, Real>> + operator()(const std::pair& pidp, + const PeriodicBoundary& pbc) const noexcept + { + if(pidp.first == ignore) {return boost::none;} + const auto rr = radius + pidp.second.radius(); + const auto rhs = pbc.periodic_transpose(pidp.second.position(), center); + const auto dist_sq = length_sq(rhs - center); + if(rr * rr < dist_sq) + { + return boost::none; + } + return std::make_pair(pidp, std::sqrt(dist_sq)); + } + + bool operator()(const AABB& box, const PeriodicBoundary& pbc) const noexcept + { + return this->distance_sq(box, center, pbc) < radius * radius; + } + + private: + + // AABB-sphere intersection query under the PBC + Real distance_sq(const AABB& box, Real3 pos, const PeriodicBoundary& pbc) const noexcept + { + pos = pbc.periodic_transpose(pos, (box.upper() + box.lower()) * 0.5); + + Real dist_sq = 0; + for(std::size_t i=0; i<3; ++i) + { + const auto v = pos[i]; + if(v < box.lower()[i]) + { + dist_sq += (v - box.lower()[i]) * (v - box.lower()[i]); + } + else if(box.upper()[i] < v) + { + dist_sq += (v - box.upper()[i]) * (v - box.upper()[i]); + } + } + return dist_sq; + } +}; + +BOOST_AUTO_TEST_CASE_TEMPLATE(PeriodicRTree_query, AABBGetter, aabb_getters) +{ + constexpr std::size_t N = 500; + constexpr Real L = 1.0; + const Real3 edge_lengths(L, 2*L, 3*L); + const PeriodicBoundary pbc(edge_lengths); + std::mt19937 mt(123456789); + std::uniform_real_distribution uni(0.0, L); + + const Species sp(""A""); + const Real radius = 0.005; + const Real D = 1.0; + + PeriodicRTree tree(edge_lengths, 0.01); + BOOST_TEST_MESSAGE(""tree constructed""); + + std::vector> full_list; + SerialIDGenerator pidgen; + for(std::size_t i=0; i, Real>> query_results; + using query_result_type = typename decltype(query_results)::value_type; + + const ParticleID nil = pidgen(); + for(const auto& pidp : full_list) + { + BOOST_REQUIRE(tree.has(pidp.first)); + BOOST_REQUIRE(tree.get(pidp.first) == pidp); + + const Query q{nil, pidp.second.position(), pidp.second.radius()}; + + tree.query(q, std::back_inserter(query_results)); + BOOST_TEST((std::find_if(query_results.begin(), query_results.end(), + [&pidp](const query_result_type& lhs) -> bool { + return lhs.first.first == pidp.first; + }) != query_results.end())); + query_results.clear(); + } + + // ---------------------------------------------------------------------- + // send a query and check all the possible collisions are detected + + for(std::size_t i=0; i bool { + return lhs.first.first == pidp.first; + }); + if(found == query_results.end()) + { + all_found = false; + } + } + } + BOOST_TEST(all_found); + query_results.clear(); + } + BOOST_TEST_MESSAGE(""query is tested""); + + // ---------------------------------------------------------------------- + // check query results after erase/insert + + for(std::size_t i=0; i bool { + return lhs.first.first == old.first; + }) == query_results.end())); + query_results.clear(); + } + + BOOST_REQUIRE(tree.diagnosis()); + + full_list.at(i).second = p; + tree.insert(full_list.at(i)); + + const auto novel = full_list.at(i); + + { + const Query q{nil, novel.second.position(), novel.second.radius()}; + tree.query(q, std::back_inserter(query_results)); + BOOST_TEST((std::find_if(query_results.begin(), query_results.end(), + [&novel](const query_result_type& lhs) -> bool { + return lhs.first.first == novel.first; + }) != query_results.end())); + query_results.clear(); + } + + BOOST_REQUIRE(tree.diagnosis()); + } + BOOST_TEST_MESSAGE(""objects are updated""); + + for(std::size_t i=0; i bool { + return lhs.first.first == pidp.first; + }); + + BOOST_CHECK(found != query_results.end()); + } + } + query_results.clear(); + } + + // ---------------------------------------------------------------------- + // update() + + for(std::size_t i=0; i bool { + return lhs.first.first == novel.first; + }) != query_results.end())); + query_results.clear(); + } + } + BOOST_TEST_MESSAGE(""objects are updated""); + + for(std::size_t i=0; i bool { + return lhs.first.first == pidp.first; + }); + + BOOST_CHECK(found != query_results.end()); + } + } + query_results.clear(); + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/Real3_test.cpp",".cpp","646","34","#define BOOST_TEST_MODULE ""Real3_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +using namespace ecell4; + + +BOOST_AUTO_TEST_CASE(Real3_test_multiply) +{ + Real3 pos1(1,2,3); + BOOST_CHECK_EQUAL(pos1 * 2, Real3(2,4,6)); +} + +BOOST_AUTO_TEST_CASE(Real3_test_add) +{ + Real3 pos2(1,2,3); + Real3 pos3(2,4,6); + BOOST_CHECK_EQUAL(pos2 + pos3, Real3(3,6,9)); +} + +BOOST_AUTO_TEST_CASE(Real3_test_sub) +{ + Real3 pos4(2,4,6); + Real3 pos5(1,2,3); + BOOST_CHECK_EQUAL(pos4 - pos5, Real3(1,2,3)); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/core/tests/Shape_test.cpp",".cpp","2245","90","#define BOOST_TEST_MODULE ""Shape_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include +#include + +using namespace ecell4; + +struct Fixture +{ + const Real3 center; + const Real radius; + Sphere sphere; + Fixture() : + center(2.5e-6, 2.5e-6, 2.5e-6), + radius(2.5e-7), sphere(center, radius) + { + } +}; + +BOOST_FIXTURE_TEST_SUITE(suite, Fixture) + +BOOST_AUTO_TEST_CASE(Shape_test_constructor) +{ +} + +BOOST_AUTO_TEST_CASE(Shape_test_is_inside) +{ + BOOST_CHECK(sphere.is_inside(center) <= 0); + BOOST_CHECK(sphere.is_inside(Real3(2.3e-6, 2.5e-6, 2.5e-6)) <= 0); + BOOST_CHECK(sphere.is_inside(Real3(2.5e-6, 2.3e-6, 2.5e-6)) <= 0); + BOOST_CHECK(sphere.is_inside(Real3(2.5e-6, 2.5e-6, 2.3e-6)) <= 0); + BOOST_CHECK(sphere.is_inside(Real3(2.2e-6, 2.5e-6, 2.5e-6)) > 0); + BOOST_CHECK(sphere.is_inside(Real3(2.5e-6, 2.2e-6, 2.5e-6)) > 0); + BOOST_CHECK(sphere.is_inside(Real3(2.5e-6, 2.5e-6, 2.2e-6)) > 0); +} + +BOOST_AUTO_TEST_SUITE_END() + + +struct RodFixture +{ + const Real3 center; + const Real length; + const Real radius; + Rod rod; + std::shared_ptr rng; + RodFixture() : + center(5e-6, 5e-6, 5e-6), length(2.5e-6), + radius(1.25e-6), rod(length, radius, center), + rng(new GSLRandomNumberGenerator()) + { + } +}; + +BOOST_FIXTURE_TEST_SUITE(rod_suite, RodFixture) + +BOOST_AUTO_TEST_CASE(Rod_test_draw_position) +{ + for (int i(0); i < 1000; ++i) + BOOST_ASSERT(rod.is_inside(rod.draw_position(rng)) <= 0); +} + +BOOST_AUTO_TEST_CASE(RodSurface_test_draw_position) +{ + RodSurface surface(rod.surface()); + int over(0), just(0), under(0); + for (int i(0); i < 1000; ++i) + { + const Real l(surface.is_inside(surface.draw_position(rng))); + if (l > radius*1e-6) + ++over; + else if (l < -radius*1e-6) + ++under; + else + ++just; + } + // std::cout << ""over: "" << over << "", just:"" << just << "", under: "" << under << std::endl; +} + +BOOST_AUTO_TEST_SUITE_END() +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/distance.hpp",".hpp","5835","240","#ifndef ECELL4_SGFRD_DISTANCE +#define ECELL4_SGFRD_DISTANCE +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +template +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const shape1& s1, const shape2& s2) const + { + throw ecell4::NotSupported( + ""distance_sq for this specific shapes is not supported""); + } +}; + +template<> +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Triangle& t) const + { + return ecell4::collision::distance_sq_point_triangle(p, t); + } +}; + +template<> +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Circle& t) const + { + return ecell4::collision::distance_sq_point_circle(p, t); + } +}; + +template<> +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Cone& t) const + { + return ecell4::collision::distance_sq_point_cone(p, t); + } +}; + +template<> +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Cylinder& t) const + { + const Real d = ecell4::collision::distance_point_cylinder(p, t); + return d*d; + } +}; + +template<> +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Sphere& s) const + { + const Real d = length(p - s.center()) - s.radius(); + return d*d; + } +}; + +template<> +struct distance_sq_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Segment& s) const + { + const Real3 ab = s.stop() - s.start(); + const Real3 ac = p - s.start(); + const Real3 bc = p - s.stop(); + const Real dot = dot_product(ac, ab); + if(dot <= 0.0){return length_sq(ac);} + const Real len = length_sq(ab); + if(dot >= len){return length_sq(bc);} + const Real ans = length_sq(ac) - (dot * dot) / len; + // for numerical robustness, distance never be negative + return std::max(ans, 0.0); + } +}; + +//---------------------------------- distance ---------------------------------- + +template +struct distance_impl +{ + typedef Real result_type; + + Real operator()(shape1 s1, shape2 s2) const + { + throw ecell4::NotSupported( + ""distance for this specific shapes is not supported""); + } +}; + +template<> +struct distance_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Triangle& t) const + { + return ecell4::collision::distance_point_triangle(p, t); + } +}; + +template<> +struct distance_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Circle& t) const + { + return ecell4::collision::distance_point_circle(p, t); + } +}; + +template<> +struct distance_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Cone& t) const + { + return ecell4::collision::distance_point_cone(p, t); + } +}; + +template<> +struct distance_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Cylinder& t) const + { + return ecell4::collision::distance_point_cylinder(p, t); + } +}; + +template<> +struct distance_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Sphere& s) const + { + return length(p - s.center()) - s.radius(); + } +}; + +template<> +struct distance_impl +{ + typedef Real result_type; + + Real operator()(const Real3& p, const ecell4::Segment& s) const + { + return std::sqrt(distance_sq_impl()(p, s)); + } +}; + +// ---------------------------------------------------------------------------- + +template +typename std::enable_if::value && + std::is_base_of::value, Real>::type +distance(const T1& shape1, const T2& shape2) +{ + return distance_impl()(shape1, shape2); +} + +template +typename std::enable_if::value, Real>::type +distance(const T& shape, const Real3& pos) +{ + return distance_impl()(pos, shape); +} + +template +typename std::enable_if::value, Real>::type +distance(const Real3& pos, const T& shape) +{ + return distance_impl()(pos, shape); +} + +inline Real distance(const Real3& lhs, const Real3& rhs) +{ + return length(lhs - rhs); +} + +template +typename std::enable_if::value && + std::is_base_of::value, Real>::type +distance_sq(const T1& shape1, const T2& shape2) +{ + return distance_sq_impl()(shape1, shape2); +} + +template +typename std::enable_if::value, Real>::type +distance_sq(const T& shape, const Real3& pos) +{ + return distance_sq_impl()(pos, shape); +} + +template +typename std::enable_if::value, Real>::type +distance_sq(const Real3& pos, const T& shape) +{ + return distance_sq_impl()(pos, shape); +} + +inline Real distance_sq(const Real3& lhs, const Real3& rhs) +{ + return length_sq(lhs - rhs); +} + +} // sgfrd +}// ecell4 +#endif// ECELL4_SGFRD_DISTANCE +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/SGFRDSimulator.hpp",".hpp","91046","2296","#ifndef ECELL4_SGFRD_SIMULATOR +#define ECELL4_SGFRD_SIMULATOR + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include + +#define SGFRD_LOG(x, y) /**/ + +namespace ecell4 +{ +namespace sgfrd +{ + +class SGFRDSimulator : + public ecell4::SimulatorBase +{ + public: + typedef SGFRDSimulator self_type; + + // polygon + typedef ecell4::Polygon polygon_type; + typedef ecell4::Triangle Triangle; + + // Event & Domain + typedef SGFRDEvent event_type; + typedef SGFRDEvent::domain_type domain_type; + typedef EventID event_id_type; + typedef DomainID domain_id_type; + typedef SGFRDEventScheduler scheduler_type; + typedef SGFRDEventScheduler::value_type event_id_pair_type; + + // Simulator + typedef ecell4::SimulatorBase base_type; + typedef base_type::world_type world_type; + typedef base_type::model_type model_type; + typedef std::pair particle_id_pair_type; + typedef std::tuple pid_p_fid_tuple_type; + // length of this type may be tuned + typedef boost::container::small_vector bursted_type; + + // ShellContainer + typedef ecell4::SerialIDGenerator shell_id_generator_type; + typedef ShellContainer shell_container_type; + typedef shell_container_type::shell_type shell_type; + typedef shell_container_type::shell_id_pair_type shell_id_pair_type; + typedef shell_container_type::circle_type circle_type; + typedef shell_container_type::conical_surface_type conical_surface_type; + typedef shell_container_type::circular_shell_type circular_shell_type; + typedef shell_container_type::conical_surface_shell_type + conical_surface_shell_type; + typedef shell_visitor_applier + mutable_shell_visitor_applier_type; + typedef shell_visitor_applier + immutable_shell_visitor_applier_type; + + // reaction + typedef ecell4::ReactionRule reaction_rule_type; + typedef ReactionInfo reaction_info_type; + typedef std::pair reaction_log_type; + typedef std::vector reaction_archive_type; + + public: + + SGFRDSimulator(const std::shared_ptr& world, + const std::shared_ptr& model, + Real bd_dt_factor = 0.01, Real reaction_length = 0.1, + const std::string& trace_fname = ""sgfrd_trace.log"") + : base_type(world, model), is_dirty_(true), dt_(0), + bd_dt_factor_(bd_dt_factor), reaction_length_(reaction_length), + rng_(*(world->rng())), shell_container_(world->polygon()), + mut_sh_vis_applier(shell_container_), imm_sh_vis_applier(shell_container_), + tracer_(trace_fname) + { + if(1.0 + reaction_length >= single_circular_shell_factor) + { + // If this condition is satisfied, sGFRD allows a single shell that + // has a reactive range outside the shell. But single domain does + // not consider reactions outside the shell, so it causes an error. + throw std::invalid_argument(""SGFRDSimulator: too large reaction length""); + } +#ifndef ECELL4_SGFRD_NO_TRACE + tracer_.clear(); // create a file and clear the file if already exists +#endif + } + + SGFRDSimulator(std::shared_ptr world, + Real bd_dt_factor = 0.01, Real reaction_length = 0.1, + const std::string& trace_fname = ""sgfrd_trace.log"") + : base_type(world), is_dirty_(true), dt_(0), + bd_dt_factor_(bd_dt_factor), reaction_length_(reaction_length), + rng_(*(world->rng())), shell_container_(world->polygon()), + mut_sh_vis_applier(shell_container_), imm_sh_vis_applier(shell_container_), + tracer_(trace_fname) + { + if(1.0 + reaction_length >= single_circular_shell_factor) + { + // If this condition is satisfied, sGFRD allows a single shell that + // has a reactive range outside the shell. But single domain does + // not consider reactions outside the shell, so it causes an error. + throw std::invalid_argument(""SGFRDSimulator: too large reaction length""); + } +#ifndef ECELL4_SGFRD_NO_TRACE + tracer_.clear(); // create a file and clear the file if already exists +#endif + } + ~SGFRDSimulator() override = default; + + void initialize() override + { + if(!(this->is_dirty_)) + { + // already initialized. do nothing. + return; + } + + // add tight shells for each particle + ParticleID pid; Particle p; + for(const auto& pidp : this->world_->list_particles()) + { + std::tie(pid, p) = pidp; + add_event(create_tight_domain(create_tight_shell( + pid, p, this->get_face_id(pid)), pid, p)); + } + + // add birth domains for each 0-th order reaction rule + for(const auto& rule : this->model_->reaction_rules()) + { + if(rule.reactants().empty()) // it is 0-th order + { + this->add_birth_event(rule); + } + } + this->is_dirty_ = false; + return ; + } + void finalize() + { + assert(this->diagnosis()); + + this->is_dirty_ = true; + + const Real tm(this->time()); + while(this->scheduler_.size() != 0) + { + this->burst_event(this->scheduler_.pop(), tm); + } + + // clear dt to correctly step in SimulatorBase::run(); + this->dt_ = 0.0; + return ; + } + void finalize(const Real t) + { + assert(this->diagnosis()); + + this->is_dirty_ = true; + + assert(t < this->next_event_time()); + const Real tm(t); + this->set_t(t); + while(this->scheduler_.size() != 0) + { + this->burst_event(this->scheduler_.pop(), tm); + } + + // clear dt to correctly step in SimulatorBase::run(); + this->dt_ = 0.0; + return ; + } + + Real next_event_time() const + { + return this->scheduler_.next_time(); + } + + void step() override + { + SGFRD_SCOPE(us, step, tracer_); + + if(this->is_dirty_) // unlikely + { + // if this simulator has been finalized (in the last step(upto)), + // re-initialize it. + this->initialize(); + } + + this->set_t(this->scheduler_.next_time()); + SGFRD_TRACE(tracer_.write(""now t = %1%"", this->time())) + + // fire event executes `create_event` inside. + this->fire_event(this->scheduler_.pop()); + SGFRD_TRACE(tracer_.write(""now %1% shells exists"", shell_container_.num_shells())) + SGFRD_TRACE(tracer_.write(""now %1% events exists"", scheduler_.size())) + + // Set the next dt_. + // This is required to run this simulator with a FixedIntervalXXXObserver. + // 1. SimulatorBase::run(obs, upto) checks whether obs.next_time() < + // `Simulator::next_time()`. + // 2. Simulator::next_time() is not virtual. So it cannot be overridden. + // 3. Simulator::next_time() returns `simulator::t() + simulator::dt()`. + this->dt_ = this->scheduler_.next_time() - this->time(); + + //XXX + assert(this->diagnosis()); + + return; + } + /** + * step and return true if the next time is less than upto. + * if not, step till upto and return false. + * @return if the simulator does not rearch upto + */ + bool step(const Real& upto) override + { + if(this->is_dirty_) + { + // if this simulator has been finalized (in the last step(upto)), + // re-initialize it. + this->initialize(); + } + + if(this->time() > upto) + { + // it's too late to stop... + return false; + } + + if(this->scheduler_.next_time() < upto) + { + // step does re-initialize inside it. + this->step(); + assert(this->time() < upto); + return true; + } + else if(this->scheduler_.next_time() == upto) // really unlikely + { + this->step(); + assert(this->time() == upto); + this->finalize(); + return false; + } + // [[assert axiom: next_time > upto]] + + // burst all the domains at t == upto. + this->finalize(upto); + return false; + } + + void set_t(const Real t) {return this->world_->set_t(t);} + + world_type const& world() const {return *(this->world_);} + + Real dt() const override {return dt_;} + Real reaction_length() const {return reaction_length_;} + + bool check_reaction() const override {return last_reactions_.size() > 0;} + std::vector > const& + last_reactions() const {return last_reactions_;} + + bool diagnosis() const; + + private: + + // simple wrappers to call member's member-method (e.g. world_->t()) {{{ + Real uniform_real(){return this->rng_.random();} + + polygon_type const& polygon() const {return *(this->world_->polygon());} + + bool update_particle(const ParticleID& pid, const Particle& p, + const FaceID& fid) + { + const bool result = this->world_->update_particle(pid, p, fid); + SGFRD_TRACE(tracer_.write("" particle %1% is updated, %2%"", pid, result)) + assert(result == false); + return result; + } + std::pair, bool> + create_particle(const Particle& p, const FaceID& fid) + { + const std::pair, bool> result = + this->world_->new_particle(p, fid); + assert(result.second); +// { +// SGFRD_TRACE(tracer_.write("" particle %1% has been created"", +// result.first.first)) +// } +// else +// { +// SGFRD_TRACE(tracer_.write("" failed to create particle %1%"", +// result.first.first)) +// } + return result; + } + void remove_particle(const ParticleID& pid, const FaceID& fid) + { + SGFRD_TRACE(tracer_.write("" removing particle %1% on face %2%"", pid, fid)); + return this->world_->remove_particle(pid, fid); + } + + shell_type& get_shell(ShellID const& id) + { + SGFRD_TRACE(tracer_.write("" searching shell %1%"", id)); + return shell_container_.get_shell(id); + } + shell_type const& get_shell(ShellID const& id) const + { + SGFRD_TRACE(tracer_.write("" searching shell %1%"", id)); + return shell_container_.get_shell(id); + } + void remove_shell(ShellID const& id) + { + SGFRD_TRACE(tracer_.write("" removing shell %1%"", id)); + return shell_container_.remove_shell(id); + } + template + void update_shell(ShellID const& shid, shT const& sh, stridT strid) + { + this->shell_container_.update_shell(shid, sh, strid); + return; + } + + FaceID get_face_id(const ParticleID& pid) const + { + if(!this->world_->is_on_face(pid)) + { + SGFRD_TRACE(tracer_.write("" particle %1% is not on face"", pid)); + SGFRD_TRACE(tracer_.write("" is particle %1% is in world?: %2%"", + pid, this->world_->has_particle(pid))); + } + return this->world_->get_face_id(pid); + } + std::pair get_particle(const ParticleID& pid) const + {return this->world_->get_particle(pid);} + + Real time() const {return this->world_->t();} + + bool event_exists(const event_id_type& id) + { + SGFRD_TRACE(tracer_.write("" checking event %1% exists or not"", id)); + try + { + std::shared_ptr ev = scheduler_.get(id); + return static_cast(ev); + } + catch(std::out_of_range const& oor) + { + return false; + } + } + + std::shared_ptr get_event(const event_id_type& id) + { + SGFRD_TRACE(tracer_.write("" getting event %1%"", id)); + return scheduler_.get(id); + } + void remove_event(const event_id_type id) + { + SGFRD_TRACE(tracer_.write("" removing event %1%"", id)); + this->scheduler_.remove(id); + return; + } + + DomainID get_domain_id(Single const& dom) const + { + return boost::apply_visitor(domain_id_getter(), get_shell(dom.shell_id())); + } + DomainID get_domain_id(Pair const& dom) const + { + return boost::apply_visitor(domain_id_getter(), get_shell(dom.shell_id())); + } + DomainID get_domain_id(Multi const& dom) const + { + return boost::apply_visitor(domain_id_getter(), + get_shell(dom.shell_ids().front())); + } + // }}} + + private: + +//----------------------------------- single ----------------------------------- + + /*! execute Event associated with Domain, remove shell, create next event. */ + void fire_single(const Single& dom, DomainID did); + bursted_type burst_single(const Single& dom, const Real tm); + + std::tuple + propagate_single( + const shell_type& sh, const Single& dom, const Real tm) + { + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + return propagate_single_circular( + boost::get(sh), dom, tm); + } + case shell_container_type::conical_shell: + { + return propagate_single_conical( + boost::get(sh), dom, tm); + } + default: + { + throw std::logic_error((boost::format( + ""boost::variant::which(): invalid value(%1%)"") % + sh.which()).str()); + } + } + } + + std::tuple + propagate_single_circular( + const circular_shell_type& sh, const Single& dom, const Real tm); + std::tuple + propagate_single_conical( + const conical_surface_shell_type& sh, const Single& dom, const Real tm); + + std::tuple + escape_single(const shell_type& sh, const Single& dom) + { + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + return escape_single_circular( + boost::get(sh), dom); + } + case shell_container_type::conical_shell: + { + return escape_single_conical( + boost::get(sh), dom); + } + default: + { + throw std::logic_error((boost::format( + ""boost::variant::which(): invalid value(%1%)"") % + sh.which()).str()); + } + } + } + + std::tuple + escape_single_circular(const circular_shell_type& sh, const Single& dom); + std::tuple + escape_single_conical(const conical_surface_shell_type& sh, const Single& dom); + + boost::container::static_vector + reaction_single(const shell_type& sh, const Single& dom, const DomainID did); + + boost::container::static_vector + attempt_reaction_single( + const shell_type& sh, const DomainID did, const Single& dom, + const ParticleID& pid, const Particle& p, const FaceID& fid); + + boost::container::static_vector + attempt_reaction_1_to_1(const ReactionRule& rule, + const shell_type& sh, const DomainID did, const Single& dom, + const ParticleID& pid, const Particle& p, const FaceID& fid); + + boost::container::static_vector + attempt_reaction_1_to_2(const ReactionRule& rule, + const shell_type& sh, const DomainID did, const Single& dom, + const ParticleID& pid, const Particle& p, const FaceID& fid); + + std::pair + create_single_circular_shell( + const std::pair& pos, const Real size, + bool check = true) + { + SGFRD_SCOPE(ns, create_single_circular_shell, tracer_); + SGFRD_TRACE(tracer_.write(""shell size = %1%"", size)) + + const ShellID id(shell_id_gen()); + const circle_type shape(size, pos.first, + polygon().triangle_at(pos.second).normal()); + if(check) + { + shell_container_.check_add_shell( + id, circular_shell_type(shape, pos.second), pos.second, + ""create_single_circular_shell""); + } + else + { + shell_container_.add_shell( + id, circular_shell_type(shape, pos.second), pos.second); + } + SGFRD_TRACE(tracer_.write(""the shell id is %1%"", id)) + return std::make_pair(id, shape); + } + std::pair + create_single_conical_surface_shell( + const VertexID& vid, const Real size, bool check = true) + { + SGFRD_SCOPE(ns, create_single_conical_shell, tracer_); + SGFRD_TRACE(tracer_.write(""vertex ID = %1%"", vid)); + SGFRD_TRACE(tracer_.write(""shell size = %1%"", size)); + + const ShellID id(shell_id_gen()); + const conical_surface_type shape(polygon().position_at(vid), + polygon().apex_angle_at(vid), size); + if(check) + { + shell_container_.check_add_shell( + id, conical_surface_shell_type(shape, vid), vid, + ""create_single_conical_shell""); + } + else // no check required. + { + shell_container_.add_shell( + id, conical_surface_shell_type(shape, vid), vid); + } + SGFRD_TRACE(tracer_.write(""the shell id is %1%"", id)); + + return std::make_pair(id, shape); + } + + Single create_single(const std::pair& sh, + const ParticleID& pid, const Particle& p) + { + SGFRD_SCOPE(ns, create_single_circular_domain, tracer_); + SGFRD_TRACE(tracer_.write(""shell shape = %1%"", sh.second)) + + const greens_functions::GreensFunction2DAbsSym + gf(/* D = */ p.D(), + /* a = */ sh.second.size() - p.radius()); + const Real t_escape = gf.drawTime(uniform_real()); + SGFRD_TRACE(tracer_.write(""calculated escape_time = %1%"", t_escape)) + + //consider whether reaction occur or not. + const Real t_reaction = draw_reaction_time(calc_k_tot( + this->model_->query_reaction_rules(p.species()))); + SGFRD_TRACE(tracer_.write(""calculated reaction_time = %1%"", t_reaction)) + + if(t_reaction < t_escape) + { + SGFRD_TRACE(tracer_.write(""single event is set as reaction"")) + return Single(Single::REACTION, t_reaction, this->time(), sh.first, + std::make_pair(pid, p)); + } + else + { + SGFRD_TRACE(tracer_.write(""single event is set as escape"")) + return Single(Single::ESCAPE, t_escape, this->time(), sh.first, + std::make_pair(pid, p)); + } + } + + Single create_single(const std::pair& sh, + const ParticleID& pid, const Particle& p) + { + SGFRD_SCOPE(ns, create_single_conical_domain, tracer_); + SGFRD_TRACE(tracer_.write(""shell shape = %1%"", sh.second)) + SGFRD_TRACE(tracer_.write(""arguments: shell ID = %2%, shell size = %2%"" + "", particle ID = %3%, Particle position = %4%"", + sh.first, sh.second.size(), pid, p.position())) + + const Real D = p.D(); + const Real a = sh.second.size() - p.radius(); + const Real phi = sh.second.apex_angle(); + const Real r0 = length( + this->polygon().periodic_transpose(p.position(), sh.second.apex()) - + sh.second.apex()); + + SGFRD_TRACE(tracer_.write(""D = %1%"", D )) + SGFRD_TRACE(tracer_.write(""r0 = %1%"", r0 )) + SGFRD_TRACE(tracer_.write(""a = %1%"", a )) + SGFRD_TRACE(tracer_.write(""phi = %1%"", phi)) + + const greens_functions::GreensFunction2DRefWedgeAbs gf(D, r0, a, phi); + const Real t_escape = gf.drawTime(uniform_real()); + + SGFRD_TRACE(tracer_.write(""calculated escape_time = %1%"", t_escape)) + + const Real t_reaction = draw_reaction_time(calc_k_tot( + this->model_->query_reaction_rules(p.species()))); + SGFRD_TRACE(tracer_.write(""calculated reaction_time = %1%"", t_reaction)) + + if(t_reaction < t_escape) + { + SGFRD_TRACE(tracer_.write(""single event is set as reaction"")) + return Single(Single::REACTION, t_reaction, this->time(), sh.first, + std::make_pair(pid, p)); + } + else + { + SGFRD_TRACE(tracer_.write(""single event is set as escape"")) + return Single(Single::ESCAPE, t_escape, this->time(), sh.first, + std::make_pair(pid, p)); + } + } + +//------------------------------------ pair ------------------------------------ + + void fire_pair(Pair& dom, DomainID did) + { + SGFRD_SCOPE(us, fire_pair, tracer_); + const greens_functions::GreensFunction2DRadAbs + gf_ipv(dom.D_ipv(), dom.kf(), dom.r0(), dom.sigma(), dom.R_ipv()); + if(dom.eventkind() == Pair::IV_UNDETERMINED) + { + SGFRD_TRACE(tracer_.write(""pair event is IV_UNDERTERMINED. "" + ""determine iv event kind here."")) + const greens_functions::GreensFunction::EventKind iv_kind = + gf_ipv.drawEventType(this->uniform_real(), dom.dt()); + if(iv_kind == greens_functions::GreensFunction::IV_ESCAPE) + { + dom.eventkind() = Pair::IV_ESCAPE; + SGFRD_TRACE(tracer_.write(""pair event kind = IV_ESCAPE"")); + } + else if(iv_kind == greens_functions::GreensFunction::IV_REACTION) + { + dom.eventkind() = Pair::IV_REACTION; + SGFRD_TRACE(tracer_.write(""pair event kind = IV_REACTION"")); + } + else + { + throw std::runtime_error(""neither Pair::IV_ESCAPE/REACTION""); + } + } + + boost::optional reactant_index(boost::none); + const ShellID sid(dom.shell_id()); + switch(dom.eventkind()) + { + case Pair::SINGLE_REACTION_1: + { + SGFRD_SCOPE(ns, case_SINGLE_REACTION_1, tracer_); + SGFRD_TRACE(tracer_.write(""pair event kind = SINGLE_REACTION_1"")); + reactant_index = 0; + // DO NOT BREAK SWITCH-CASE HERE! + } + case Pair::SINGLE_REACTION_2: + { + SGFRD_SCOPE(ns, case_SINGLE_REACTION_2, tracer_); + if(!reactant_index) + { + SGFRD_TRACE(tracer_.write( + ""pair event kind = SINGLE_REACTION_2"")); + reactant_index = 1; + } + + // first, update 2 particles + std::array, 2> + propagated = this->propagate_pair( + this->get_shell(sid), dom, this->time()); + SGFRD_TRACE(tracer_.write(""particles are propagated"")); + + this->remove_shell(sid); + SGFRD_TRACE(tracer_.write(""shell %1% removed"", sid)); + + std::array sids; + std::array dids; + std::array doms; + std::array pids; + std::array ps; + std::array fids; + + // add tight-domain for them to detect overlap + for(std::size_t i=0; i<2; ++i) + { + std::tie(pids[i], ps[i], fids[i]) = propagated[i]; + SGFRD_TRACE(tracer_.write(""adding tight domain > %1%"", pids[i])) + sids[i] = create_tight_shell(pids[i], ps[i], fids[i]); + doms[i] = create_tight_domain(sids[i], pids[i], ps[i]); + dids[i] = add_event(doms[i]); + } + SGFRD_TRACE(tracer_.write(""tight-domains assigned"")); + + // after that, attempt single reaction + const std::size_t ridx = *reactant_index; + SGFRD_TRACE(tracer_.write(""reactant_index = %1%"", ridx)); + + auto results = this->attempt_reaction_single( + this->get_shell(sids[ridx]), dids[ridx], doms[ridx], + pids[ridx], ps[ridx], fids[ridx]); + + if(results.size() != 1 || std::get<0>(results.front()) != pids[ridx]) + { + STAT(stat_reaction_condition.add_count(PairFirstOrder)); + } + else // reaction fails. + { + STAT(stat_reaction_condition.add_count(PairFirstOrderFailed)); + } + + this->remove_shell(sids[ridx]); + SGFRD_TRACE(tracer_.write(""shell %1% removed"", sids[ridx])); + this->remove_event(dids[ridx]); + SGFRD_TRACE(tracer_.write(""event %1% removed"", dids[ridx])); + + SGFRD_TRACE(tracer_.write(""reaction attempted"")); + + // add domain to each reactant + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : results) + { + std::tie(pid, p, fid) = pidpf; + SGFRD_TRACE(tracer_.write(""adding next event for %1%"", pid)) + add_event(create_tight_domain( + create_tight_shell(pid, p, fid), pid, p)); + } + return; + } + case Pair::COM_ESCAPE: // fallthrough + case Pair::IV_ESCAPE: + { + SGFRD_SCOPE(ns, case_COM_OR_IV_ESCAPE, tracer_); + std::array, 2> + escaped = this->escape_pair( // dispatch com/ipv here + this->get_shell(sid), dom, this->time()); + SGFRD_TRACE(tracer_.write(""particles escaped"")); + + this->remove_shell(sid); + SGFRD_TRACE(tracer_.write(""shell %1% removed"", sid)); + + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : escaped) + { + std::tie(pid, p, fid) = pidpf; + SGFRD_TRACE(tracer_.write(""adding next event for %1%"", pid)) + add_event(create_tight_domain( + create_tight_shell(pid, p, fid), pid, p)); + } + return; + } + case Pair::IV_REACTION: + { + SGFRD_SCOPE(ns, case_IV_REACTION, tracer_); + boost::container::small_vector< + std::tuple, 2> + products = this->attempt_pair_reaction( + this->get_shell(sid), dom, this->time()); + SGFRD_TRACE(tracer_.write(""iv reaction attempted"")); + this->remove_shell(sid); + SGFRD_TRACE(tracer_.write(""shell %1% removed"", sid)); + + if(!products.empty()) + { + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : products) + { + std::tie(pid, p, fid) = pidpf; + SGFRD_TRACE(tracer_.write(""adding next event for %1%"", pid)); + add_event(create_tight_domain( + create_tight_shell(pid, p, fid), pid, p)); + } + } + return; + } + default: + { + throw std::invalid_argument(""fire_pair(): invalid event kind""); + } + } + } + + bursted_type burst_pair(const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, burst_pair, tracer_); + const ShellID sid(dom.shell_id()); + SGFRD_TRACE(tracer_.write(""pair shell id = %1%"", sid)); + + // no reaction occurs because `burst` occurs before any other event. + bursted_type results; + std::array, 2> + propagated(this->propagate_pair(this->get_shell(sid), dom, tm)); + results.push_back(propagated[0]); + results.push_back(propagated[1]); + + SGFRD_TRACE(tracer_.write(""particle %1% and %2% propagated"", + std::get<0>(propagated[0]), std::get<0>(propagated[1]))); + + this->remove_shell(sid); + SGFRD_TRACE(tracer_.write(""shell(%1%) removed"", sid)); + return results; + } + + std::array, 2> + propagate_pair(const shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, propagate_pair, tracer_); + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + return propagate_circular_pair( + boost::get(sh), dom, tm); + } + default: + { + throw std::logic_error((boost::format( + ""propagate_pair: shell::which() returns invalid value(%1%)"") + % sh.which()).str()); + } + } + } + + std::array, 2> + propagate_circular_pair(const circular_shell_type& sh, + const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, propagate_circular_pair, tracer_); + + // calculate displacements + const Real dt = tm - dom.begin_time(); + const greens_functions::GreensFunction2DRadAbs + gf_ipv(dom.D_ipv(), dom.kf(), dom.r0(), dom.sigma(), dom.R_ipv()); + const Real l_ipv = gf_ipv.drawR(this->uniform_real(), dt); + const Real theta_ipv = (this->uniform_real() < 0.5 ? -1.0 : 1.0) * + gf_ipv.drawTheta(this->uniform_real(), l_ipv, dt); + + const greens_functions::GreensFunction2DAbsSym + gf_com(dom.D_com(), dom.R_com()); + const Real l_com = gf_com.drawR(this->uniform_real(), dt); + const Real theta_com = this->uniform_real() * + boost::math::constants::two_pi(); + + const FaceID sh_fid = sh.structure_id(); + const Triangle& f = this->polygon().triangle_at(sh_fid); + const Real3 direction_com = rotate(theta_com, f.normal(), f.represent()); + + const Real3 disp_com = direction_com * (l_com / length(direction_com)); + const Real3 disp_ipv = rotate(theta_ipv, f.normal(), dom.ipv()) * + (l_ipv / length(dom.ipv())); + + // update position + // XXX to treat polygon surface structure, calculate displacement for + // each partile without polygon information first + // and then apply it to each particle with structure + + Particle p1 = dom.particle_at(0); + Particle p2 = dom.particle_at(1); + const ParticleID pid1 = dom.particle_id_at(0); + const ParticleID pid2 = dom.particle_id_at(1); + + // ipv is a vector from p1 to p2 + const Real rD12 = 1.0 / (p1.D() + p2.D()); + const Real3 disp_ipv_p1 = disp_ipv * (-p1.D() * rD12); + const Real3 disp_ipv_p2 = disp_ipv * ( p2.D() * rD12); + + Real3 disp_p1 = disp_com + disp_ipv_p1; + Real3 disp_p2 = disp_com + disp_ipv_p2; + // start from CoM + std::pair pos_p1(sh.position(), sh.structure_id()); + std::pair pos_p2(sh.position(), sh.structure_id()); + + pos_p1 = ecell4::polygon::travel(this->polygon(), pos_p1, disp_p1, 2); + pos_p2 = ecell4::polygon::travel(this->polygon(), pos_p2, disp_p2, 2); + + p1.position() = pos_p1.first; + p2.position() = pos_p2.first; + + this->update_particle(pid1, p1, pos_p1.second); + this->update_particle(pid2, p2, pos_p2.second); + + std::array, 2> results; + results[0] = std::make_tuple(pid1, p1, pos_p1.second); + results[1] = std::make_tuple(pid2, p2, pos_p2.second); + + // check particles are still inside of the shell after this propagation + assert( + ecell4::polygon::distance(this->polygon(), pos_p1, + std::make_pair(sh.position(), sh.structure_id())) <= + sh.size() - p1.radius() + ); + assert( + ecell4::polygon::distance(this->polygon(), pos_p2, + std::make_pair(sh.position(), sh.structure_id())) <= + sh.size() - p2.radius() + ); + return results; + } + + std::array, 2> + escape_pair(const shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, escape_pair, tracer_); + switch(dom.eventkind()) + { + case Pair::COM_ESCAPE: + { + return escape_com_pair(sh, dom, tm); + } + case Pair::IV_ESCAPE: + { + return escape_ipv_pair(sh, dom, tm); + } + default: + { + throw std::invalid_argument(""escape_pair(): invalid event kind""); + } + } + } + // center of mass escapes from inner-domain + std::array, 2> + escape_com_pair(const shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, escape_com_pair, tracer_); + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + return escape_com_circular_pair( + boost::get(sh), dom, tm); + } + default: + { + throw std::logic_error((boost::format( + ""boost::variant::which(): invalid value(%1%)"") % + sh.which()).str()); + } + } + } + // inter particle vector become too long to react each other + std::array, 2> + escape_com_circular_pair( + const circular_shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, escape_com_circular_pair, tracer_); + + // calculate displacements + const Real dt = tm - dom.begin_time(); + const greens_functions::GreensFunction2DRadAbs + gf_ipv(dom.D_ipv(), dom.kf(), dom.r0(), dom.sigma(), dom.R_ipv()); + + const Real l_ipv = gf_ipv.drawR (this->uniform_real(), dt); + const Real theta_ipv = gf_ipv.drawTheta(this->uniform_real(), l_ipv, dt) * + (uniform_real() < 0.5 ? -1 : 1) ; + // drawTheta returns value in [0, pi]. we need to determine the directionality. + const Real l_com = dom.R_com(); + const Real theta_com = this->uniform_real() * + boost::math::constants::two_pi(); + + SGFRD_TRACE(tracer_.write(""r_ipv = %1%, r_com = %2%"", dom.R_ipv(), dom.R_com())); + SGFRD_TRACE(tracer_.write(""l_ipv = %1%, theta_ipv = %2%"", l_ipv, theta_ipv)); + SGFRD_TRACE(tracer_.write(""l_com = %1%, theta_com = %2%"", l_com, theta_com)); + + const FaceID sh_fid = sh.structure_id(); + const Triangle& f = this->polygon().triangle_at(sh_fid); + + const Real3 direction_com = rotate(theta_com, f.normal(), f.represent()); + const Real3 disp_com = direction_com * (l_com / length(direction_com)); + const Real3 disp_ipv = rotate(theta_ipv, f.normal(), dom.ipv()) * + (l_ipv / length(dom.ipv())); + SGFRD_TRACE(tracer_.write(""length of disp_ipv = %1%"", length(disp_ipv))); + + // update position + // XXX to treat polygon surface structure, calculate displacement for + // each partile without polygon information first + // and then apply it to each particle with structure + + Particle p1 = dom.particle_at(0); + Particle p2 = dom.particle_at(1); + const ParticleID pid1 = dom.particle_id_at(0); + const ParticleID pid2 = dom.particle_id_at(1); + + const std::pair pos_com(sh.position(), sh.structure_id()); + + // ipv is a vector from p1 to p2 + const Real3 disp_p1 = disp_com + disp_ipv * (-p1.D() / (p1.D() + p2.D())); + const Real3 disp_p2 = disp_com + disp_ipv * ( p2.D() / (p1.D() + p2.D())); + std::pair pos_p1(pos_com); + std::pair pos_p2(pos_com); + SGFRD_TRACE(tracer_.write(""p1 is on face %1%, p2 is on face %2%"", + get_face_id(pid1), get_face_id(pid2))) + + pos_p1 = ecell4::polygon::travel(this->polygon(), pos_p1, disp_p1, 2); + pos_p2 = ecell4::polygon::travel(this->polygon(), pos_p2, disp_p2, 2); + + // check distance between p1 and p2; it should be the same as l_ipv + SGFRD_TRACE(tracer_.write(""distance after travel = %1%"", + ecell4::polygon::distance(this->polygon(), pos_p1, pos_p2))) + assert(std::abs(ecell4::polygon::distance( + this->polygon(), pos_p1, pos_p2) - l_ipv) < l_ipv * 1e-6); + + p1.position() = pos_p1.first; + p2.position() = pos_p2.first; + + this->update_particle(pid1, p1, pos_p1.second); + this->update_particle(pid2, p2, pos_p2.second); + + std::array, 2> results; + results[0] = std::make_tuple(pid1, p1, pos_p1.second); + results[1] = std::make_tuple(pid2, p2, pos_p2.second); + + // check particles are still inside of the shell after this propagation + assert( + ecell4::polygon::distance(this->polygon(), pos_p1, + std::make_pair(sh.position(), sh.structure_id())) <= + sh.size() - p1.radius() + ); + assert( + ecell4::polygon::distance(this->polygon(), pos_p2, + std::make_pair(sh.position(), sh.structure_id())) <= + sh.size() - p2.radius() + ); + + return results; + } + + std::array, 2> + escape_ipv_pair(const shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, escape_ipv_pair, tracer_); + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + return escape_ipv_circular_pair( + boost::get(sh), dom, tm); + } + default: + { + throw std::logic_error((boost::format( + ""boost::variant::which(): invalid value(%1%)"") % + sh.which()).str()); + } + } + } + std::array, 2> + escape_ipv_circular_pair( + const circular_shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, escape_ipv_circular_pair, tracer_); + // calculate length and direction of inter particle vector + const Real dt = tm - dom.begin_time(); + const greens_functions::GreensFunction2DRadAbs + gf_ipv(dom.D_ipv(), dom.kf(), dom.r0(), dom.sigma(), dom.R_ipv()); + const Real l_ipv = dom.R_ipv(); + const Real theta_ipv = gf_ipv.drawTheta(this->uniform_real(), l_ipv, dt) * + (uniform_real() < 0.5 ? -1 : 1) ; + + // calculate position of the center of mass + const greens_functions::GreensFunction2DAbsSym + gf_com(dom.D_com(), dom.R_com()); + const Real l_com = gf_com.drawR(this->uniform_real(), dt); + const Real theta_com = this->uniform_real() * + boost::math::constants::two_pi(); + + assert(l_com <= dom.R_com()); + + SGFRD_TRACE(tracer_.write(""r_ipv = %1%, r_com = %2%"", dom.R_ipv(), dom.R_com())); + SGFRD_TRACE(tracer_.write(""l_ipv = %1%, theta_ipv = %2%"", l_ipv, theta_ipv)); + SGFRD_TRACE(tracer_.write(""l_com = %1%, theta_com = %2%"", l_com, theta_com)); + + const FaceID sh_fid = sh.structure_id(); + const Triangle& f = this->polygon().triangle_at(sh_fid); + const Real3 direction_com = rotate(theta_com, f.normal(), f.represent()); + + const Real3 disp_com = direction_com * (l_com / length(direction_com)); + const Real3 disp_ipv = rotate(theta_ipv, f.normal(), dom.ipv()) * + (l_ipv / length(dom.ipv())); + SGFRD_TRACE(tracer_.write(""length of disp_com = %1%"", length(disp_com))); + SGFRD_TRACE(tracer_.write(""length of disp_ipv = %1%"", length(disp_ipv))); + + // update position + // XXX to treat polygon surface structure, calculate displacement for + // each partile without polygon information first + // and then apply it to each particle with structure + + Particle p1 = dom.particle_at(0); + Particle p2 = dom.particle_at(1); + const ParticleID pid1 = dom.particle_id_at(0); + const ParticleID pid2 = dom.particle_id_at(1); + + assert(!(p1.D() == 0.0 && p2.D() == 0.0)); + SGFRD_TRACE(tracer_.write(""previous position of p1 = %1%"", p1.position())); + SGFRD_TRACE(tracer_.write(""previous position of p2 = %1%"", p2.position())); + + const Real3& pos_com(sh.position()); + const FaceID& fid_com(sh.structure_id()); + // ipv is a vector from p1 to p2 + Real3 disp_p1 = disp_com + disp_ipv * (-p1.D() / (p1.D() + p2.D())); + Real3 disp_p2 = disp_com + disp_ipv * ( p2.D() / (p1.D() + p2.D())); + std::pair pos_p1(pos_com, fid_com); + std::pair pos_p2(pos_com, fid_com); + + pos_p1 = ecell4::polygon::travel(this->polygon(), pos_p1, disp_p1, 2); + pos_p2 = ecell4::polygon::travel(this->polygon(), pos_p2, disp_p2, 2); + + SGFRD_TRACE(tracer_.write(""position of p1 after reaction = %1%"", pos_p1.first)); + SGFRD_TRACE(tracer_.write(""position of p2 after reaction = %1%"", pos_p2.first)); + + p1.position() = pos_p1.first; + p2.position() = pos_p2.first; + + this->update_particle(pid1, p1, pos_p1.second); + this->update_particle(pid2, p2, pos_p2.second); + + std::array, 2> results; + results[0] = std::make_tuple(pid1, p1, pos_p1.second); + results[1] = std::make_tuple(pid2, p2, pos_p2.second); + + // check particles are still inside of the shell after this propagation + assert( + ecell4::polygon::distance(this->polygon(), pos_p1, + std::make_pair(sh.position(), sh.structure_id())) <= + sh.size() - p1.radius() + ); + assert( + ecell4::polygon::distance(this->polygon(), pos_p2, + std::make_pair(sh.position(), sh.structure_id())) <= + sh.size() - p2.radius() + ); + + return results; + } + + boost::container::small_vector, 2> + attempt_pair_reaction(const shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, attempt_pair_reaction, tracer_); + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + return attempt_circular_pair_reaction( + boost::get(sh), dom, tm); + } + default: + { + throw std::logic_error((boost::format( + ""boost::variant::which(): invalid value(%1%)"") % + sh.which()).str()); + } + } + } + + boost::container::small_vector, 2> + attempt_circular_pair_reaction( + const circular_shell_type& sh, const Pair& dom, const Real tm) + { + SGFRD_SCOPE(us, attempt_circular_pair_reaction, tracer_); + // 1. update one with com diffusion + // 2. mutate the particle to product + // 3. and remove the other one + + Particle p1 = dom.particle_at(0); + Particle p2 = dom.particle_at(1); + const ParticleID pid1 = dom.particle_id_at(0); + const ParticleID pid2 = dom.particle_id_at(1); + const FaceID fid1 = this->get_face_id(pid1); + const FaceID fid2 = this->get_face_id(pid2); + + const auto& rules = this->model_->query_reaction_rules( + p1.species(), p2.species()); + assert(!rules.empty()); + + const Real k_tot = this->calc_k_tot(rules); + boost::optional optr(boost::none); + if(rules.size() != 1) + { + Real rndr = this->uniform_real() * k_tot; + for(const auto& rl : rules) + { + rndr -= rl.k(); + if(rndr < 0.0) + { + optr = rl; + break; + } + } + // optr maybe empty because of numerical error. in that case, + // use domain.reactants().back(). + // if domain.reactions().size() == 1, it is okay to use + // domain.reactants().back() because it is the only rule + // that can be applied. + } + ReactionRule const& rule = static_cast(optr) ? *optr : (rules.back()); + + switch(rule.products().size()) + { + case 0: + { + SGFRD_TRACE(tracer_.write(""degradation reaction occurs."")) + + this->remove_particle(pid1, fid1); + this->remove_particle(pid2, fid2); + last_reactions_.push_back(std::make_pair(rule, + make_degradation_reaction_info(tm, pid1, p1, pid2, p2))); + + STAT(stat_reaction_condition.add_count(PairSecondOrder)); + + return boost::container::small_vector< + std::tuple, 2>(0ul); + } + case 1: + { + SGFRD_TRACE(tracer_.write(""2->1 reaction occurs."")) + + // calculate next position of particle pair + const Real dt = tm - dom.begin_time(); + const greens_functions::GreensFunction2DAbsSym + gf_com(dom.D_com(), dom.R_com()); + const Real l_com = gf_com.drawR(this->uniform_real(), dt); + const Real theta_com = this->uniform_real() * + boost::math::constants::two_pi(); + + const FaceID sh_fid = sh.structure_id(); + const Triangle& f = this->polygon().triangle_at(sh_fid); + const Real3 direction_com = + rotate(theta_com, f.normal(), f.represent()); + + Real3 disp_com = direction_com * (l_com / length(direction_com)); + std::pair pos_com(sh.position(), sh_fid); + + pos_com = ecell4::polygon::travel(this->polygon(), pos_com, disp_com, 2); + + const Real3 pos_new = pos_com.first; + const FaceID fid_new = pos_com.second; + + // make new particle + const auto species_new = rule.products().front(); + const auto molinfo = this->world_->get_molecule_info(species_new); + const Real radius_new = molinfo.radius; + const Real D_new = molinfo.D; + const Particle p_new(species_new, pos_new, radius_new, D_new); + + inside_checker is_inside_of( + p_new.position(), p_new.radius(), fid_new, this->polygon()); + if(!is_inside_of(sh)) + { + // particle sticks out from the shell after reaction + // because of its radius. + + SGFRD_SCOPE(us, particle_goes_outside, tracer_) + const DomainID did = this->get_domain_id(dom); + + const bool no_overlap = + this->burst_and_shrink_overlaps(p_new, fid_new, did); + SGFRD_TRACE(tracer_.write(""no_overlap = %1%"", no_overlap)) + + // particle overlaps with other particle/domain outside the + // shell. rollback the state. + if(!no_overlap) + { + SGFRD_TRACE(tracer_.write( + ""reject the reaction because of no space"")) + const greens_functions::GreensFunction2DRadAbs + gf_ipv(dom.D_ipv(), dom.kf(), dom.r0(), dom.sigma(), + dom.R_ipv()); + const Real theta_ipv = gf_ipv.drawTheta( + this->uniform_real(), dom.sigma(), dt) * + (uniform_real() < 0.5 ? -1 : 1); + const Real3 disp_ipv = + rotate(theta_ipv, f.normal(), dom.ipv()); + + // TODO make function like + // propagate_pair(ipv0, disp_com, ipv1) + const Real ratio_p1 = -p1.D() / (p1.D() + p2.D()); + const Real ratio_p2 = p2.D() / (p1.D() + p2.D()); + const Real3 disp_ipv_p1 = disp_ipv * ratio_p1; + const Real3 disp_ipv_p2 = disp_ipv * ratio_p2; + const Real3 disp_ipv0_p1 = dom.ipv() * ratio_p1; + const Real3 disp_ipv0_p2 = dom.ipv() * ratio_p2; + + Real3 disp_p1 = disp_com - disp_ipv0_p1 + disp_ipv_p1; + Real3 disp_p2 = disp_com - disp_ipv0_p2 + disp_ipv_p2; + disp_p1 *= (1. + minimum_separation_factor / 2); + disp_p2 *= (1. + minimum_separation_factor / 2); + + std::pair pos_p1(p1.position(), fid1); + std::pair pos_p2(p2.position(), fid2); + pos_p1 = ecell4::polygon::travel(this->polygon(), pos_p1, disp_p1, 2); + pos_p2 = ecell4::polygon::travel(this->polygon(), pos_p2, disp_p2, 2); + + p1.position() = pos_p1.first; + p2.position() = pos_p2.first; + this->update_particle(pid1, p1, pos_p1.second); + this->update_particle(pid2, p2, pos_p2.second); + + boost::container::small_vector< + std::tuple, 2 + > results(2); + results[0] = std::make_tuple(pid1, p1, pos_p1.second); + results[1] = std::make_tuple(pid2, p2, pos_p2.second); + + STAT(stat_reaction_condition.add_count(PairSecondOrderFailed)); + return results; + } + } + SGFRD_TRACE(tracer_.write(""reaction is accepted."")) + this->update_particle(pid1, p_new, fid_new); + + this->remove_particle(pid2, fid2); + last_reactions_.push_back(std::make_pair(rule, + make_binding_reaction_info( + tm, pid1, p1, pid2, p2, pid1, p_new))); + + // reaction succeed. + STAT(stat_reaction_condition.add_count(PairSecondOrder)); + + boost::container::small_vector< + std::tuple, 2> retval(1ul); + retval[0] = std::make_tuple(pid1, p_new, fid_new); + return retval; + } + default: + { + throw NotImplemented(""SGFRD Pair Reaction: "" + ""more than two products from one reactant are not allowed""); + } + } + } + + Pair create_pair(const std::pair& sh, + const ParticleID& pid1, const Particle& p1, + const ParticleID& pid2, const Particle& p2, + const Real3& ipv, const Real len_ipv) + { + SGFRD_SCOPE(ns, create_circular_pair_domain, tracer_); + + SGFRD_TRACE(tracer_.write(""shell size = %1%"", sh.second.size())) + SGFRD_TRACE(tracer_.write(""D1 = %1%, D2 = %2%"", p1.D(), p2.D())) + SGFRD_TRACE(tracer_.write(""r1 = %1%, r2 = %2%"", p1.radius(), p2.radius())) + + // ------------------ GF event (escape | ipv) -------------------------- + + // the effective shell size is smaller than the actual shell size + // by the radius of particles inside + const Real shell_size = sh.second.size() - std::max(p1.radius(), p2.radius()); + + const greens_functions::GreensFunction2DAbsSym + gf_com(Pair::calc_D_com(p1.D(), p2.D()), + Pair::calc_R_com(shell_size, p1, p2)); + const Real t_com_escape = gf_com.drawTime(this->uniform_real()); + + const Real k_tot = this->calc_k_tot(this->model_->query_reaction_rules( + p1.species(), p2.species())); + SGFRD_TRACE(tracer_.write(""ipv length = %1%"", len_ipv)) + SGFRD_TRACE(tracer_.write(""total rate = %1%"", k_tot)) + + // TODO: [perf] if k_tot == 0.0 then we don't need GF. + const greens_functions::GreensFunction2DRadAbs + gf_ipv(Pair::calc_D_ipv(p1.D(), p2.D()), + k_tot, len_ipv, p1.radius() + p2.radius(), + Pair::calc_R_ipv(shell_size, p1, p2)); + const Real t_ipv_event = gf_ipv.drawTime(this->uniform_real()); + + const std::pair gf_event( + (t_ipv_event < t_com_escape) ? + std::make_pair(t_ipv_event, Pair::IV_UNDETERMINED) : + std::make_pair(t_com_escape, Pair::COM_ESCAPE)); + + SGFRD_TRACE(tracer_.write(""com escape time = %1%"", t_com_escape)) + SGFRD_TRACE(tracer_.write(""ipv event time = %1%"", t_ipv_event)) + SGFRD_TRACE(tracer_.write(""GF event time = %1%"", gf_event.first)) + + // ------------------- single reaction event --------------------------- + + const Real t_single_reaction_1 = this->draw_reaction_time( + this->calc_k_tot(this->model_->query_reaction_rules(p1.species()))); + const Real t_single_reaction_2 = this->draw_reaction_time( + this->calc_k_tot(this->model_->query_reaction_rules(p2.species()))); + + const std::pair single_event( + (t_single_reaction_1 < t_single_reaction_2) ? + std::make_pair(t_single_reaction_1, Pair::SINGLE_REACTION_1) : + std::make_pair(t_single_reaction_2, Pair::SINGLE_REACTION_2)); + + SGFRD_TRACE(tracer_.write(""particle 1 single reaction time = %1%"", t_single_reaction_1)) + SGFRD_TRACE(tracer_.write(""particle 2 single reaction time = %1%"", t_single_reaction_2)) + SGFRD_TRACE(tracer_.write(""single reaction time = %1%"", single_event.first)) + + // -------------------------------------------------------------------- + + if(gf_event.first < single_event.first) + { + SGFRD_TRACE(tracer_.write(""gf event occurs first"")) + return Pair(gf_event.second, gf_event.first, this->time(), sh.first, + shell_size, + std::make_pair(pid1, p1), + std::make_pair(pid2, p2), + len_ipv, ipv, k_tot); + } + else + { + SGFRD_TRACE(tracer_.write(""single reaction occurs first"")) + return Pair(single_event.second, single_event.first, this->time(), + sh.first, + shell_size, + std::make_pair(pid1, p1), + std::make_pair(pid2, p2), + len_ipv, ipv, k_tot); + } + } + + +//----------------------------------- multi ------------------------------------ + + void fire_multi(Multi& dom, DomainID did) + { + SGFRD_SCOPE(us, fire_multi, tracer_); + SGFRD_TRACE(tracer_.write(""fire multi(%1%) for default dt(%2%)"", did, dom.dt())); + + STAT(stat_multi_size.add_count(dom.particles().size());) + + volume_clearer vc(did, dom, *this, this->imm_sh_vis_applier); + dom.step(vc); + switch(dom.eventkind()) + { + case Multi::NONE: + { + SGFRD_TRACE(tracer_.write(""nothing occurs"")) + /* continuing multi domain: add this domain to scheduler */ + dom.begin_time() = this->time(); + this->add_event(dom); + return; + } + case Multi::REACTION: + { + SGFRD_TRACE(tracer_.write(""reaction occurs {""); + for(auto rrec : dom.last_reactions()) + { + tracer_.write(""rule: %1% t: %2% reactant: { "", + rrec.first.as_string(), rrec.second.t()); + for(auto reactant : rrec.second.reactants()) + { + tracer_.write(""%1% "", reactant.first); + } + tracer_.write(""} products: { ""); + for(auto product: rrec.second.products()) + { + tracer_.write(""%1% "", product.first); + } + tracer_.write(""}""); + } + tracer_.write(""}"");) + + std::copy(dom.last_reactions().begin(), dom.last_reactions().end(), + std::back_inserter(this->last_reactions_)); + + // record statistics + for(const auto& rrec : dom.last_reactions()) + { + if(rrec.second.reactants().size() == 1) + { + STAT(stat_reaction_condition.add_count(MultiFirstOrder)); + } + else if(rrec.second.reactants().size() == 2) + { + STAT(stat_reaction_condition.add_count(MultiSecondOrder)); + } + else + { + throw std::runtime_error(""unknown reaction record found""); + } + } + + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : this->remove_multi(dom)) + { + std::tie(pid, p, fid) = pidpf; + this->add_event(this->create_tight_domain( + this->create_tight_shell(pid, p, fid), pid, p)); + } + SGFRD_TRACE(tracer_.write(""multi domain (id = %1%) removed."", did)) + return; + } + case Multi::ESCAPE: + { + SGFRD_TRACE(tracer_.write(""escape occurs"")) + /* burst this domain! */ + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : this->remove_multi(dom)) + { + std::tie(pid, p, fid) = pidpf; + this->add_event(this->create_tight_domain( + this->create_tight_shell(pid, p, fid), pid, p)); + } + SGFRD_TRACE(tracer_.write(""multi domain (id = %1%) removed."", did)) + return; + } + default: + { + SGFRD_TRACE(tracer_.write(""Multi eventkind become invalid value!"")) + throw std::logic_error(""never reach here""); + } + } + } + + // simply remove all the shells. not add a domains for each particles. + // particles are updated at each step, so here nothing is needed to + // update world. + bursted_type remove_multi(const Multi& dom) + { + SGFRD_SCOPE(ns, remove_multi, tracer_); + bursted_type results; + Particle p; ParticleID pid; + for(const auto& pidp : dom.particles()) + { + std::tie(pid, p) = pidp; + results.push_back(std::make_tuple(pid, p, this->get_face_id(pid))); + } + + SGFRD_TRACE(tracer_.write(""particles are collected"")) + + for(const ShellID& sid : dom.shell_ids()) + { + this->remove_shell(sid); + } + SGFRD_TRACE(tracer_.write(""shells are removed"")) + return results; + } + + // burst. step until(tm - dom.begin_time()). + bursted_type burst_multi(Multi& dom, const Real tm) + { + SGFRD_SCOPE(ns, burst_multi, tracer_); + + auto did = get_domain_id(dom); + volume_clearer vc(did, dom, *this, this->imm_sh_vis_applier); + dom.step(vc, tm - dom.begin_time()); + + SGFRD_TRACE(tracer_.write(""multi domain steps with delta_t = %1%"", + tm - dom.begin_time())); + + if(dom.eventkind() == Multi::REACTION) + { + SGFRD_TRACE(tracer_.write(""reaction occured"")); + std::copy(dom.last_reactions().begin(), dom.last_reactions().end(), + std::back_inserter(this->last_reactions_)); + } + return remove_multi(dom); + } + +//----------------------------------- birth ------------------------------------ + + void fire_birth(const Birth& dom, DomainID did) + { + SGFRD_SCOPE(ns, fire_birth, tracer_); + + const auto& rule = dom.rule(); + assert(rule.products().size() == 1); + + const auto& sp = rule.products().front(); + const auto molinfo = this->world_->get_molecule_info(sp); + + constexpr std::size_t max_retry_position = 1000; // 1 means no retry. + for(std::size_t i = 0; i < max_retry_position; ++i) + { + FaceID fid; + const Real3 pos = this->polygon().draw_position(this->world_->rng(), fid); + const Particle p(sp, pos, molinfo.radius, molinfo.D); + + const bool no_overlap = this->burst_and_shrink_overlaps(p, fid, did); + if(no_overlap) + { + const auto pp = this->create_particle(p, fid); + assert(pp.second); + + const auto pid = pp.first.first; + + // record this birth reaction + last_reactions_.emplace_back(rule, make_synthesis_reaction_info( + this->time(), pid, pp.first.second)); + + // add tight shell for the new particle + add_event(create_tight_domain( + create_tight_shell(pid, p, fid), pid, p)); + break; + } + } + + // anyway, re-register the Birth reaction for the next time + + add_birth_event(rule); + return; + } + + DomainID add_birth_event(const ReactionRule& rule) + { + const auto rnd = this->rng_.uniform(0, 1); + const auto dt = std::log(1.0 / rnd) / + (rule.k() * this->polygon().total_area()); + Birth new_event(dt, this->time(), rule); + return this->add_event(new_event); + } + +// ----------------------------------------------------------------------------- + + // XXX: Note that the second element, distance to the domain, is + // - a distance to the Multi domains that ware not bursted or + // - a distance to the min-shell of particles that were bursted. + std::vector > + burst_and_shrink_non_multis( + const ParticleID& pid, const Particle& p, const FaceID& fid, + const std::vector >& intruders) + { + SGFRD_SCOPE(us, burst_and_shrink_non_multis, tracer_) + + const Real tm(this->time()); + std::vector > results; + + DomainID did; Real dist; + for(const auto& didd : intruders) + { + SGFRD_SCOPE(ns, loop_for_intruders, tracer_) + + std::tie(did, dist) = didd; + const auto& ev = get_event(did); + if(ev->which_domain() == event_type::multi_domain) + { + SGFRD_TRACE(tracer_.write(""domain %1% is multi"", did)) + results.push_back(std::make_pair(did, dist)); + continue; + } + SGFRD_TRACE(tracer_.write(""domain %1% is not a multi"", did)) + + DomainID did_; ParticleID pid_; Particle p_; FaceID fid_; + for(const auto& pidpf : burst_event(std::make_pair(did, ev), tm)) + { + std::tie(pid_, p_, fid_) = pidpf; + + SGFRD_TRACE(tracer_.write( + ""add tight domain to bursted particle %1%"", pid_)) + did_ = add_event(create_tight_domain( + create_tight_shell(pid_, p_, fid_), pid_, p_)); + + // distance between the nearest one + const auto dist = ecell4::polygon::distance(this->polygon(), + std::make_pair(p.position(), fid), + std::make_pair(p_.position(), fid_)); + + // min shell radius of the nearest one + const auto min_shell_rad = + calc_min_single_circular_shell_radius(p_) * + single_circular_shell_factor; + + // calculate distance as if the nearest one has a minimum shell + results.emplace_back(did_, dist - min_shell_rad); + } + remove_event(did); + SGFRD_TRACE(tracer_.write(""domain %1% is bursted and shrinked"", did)) + } + + std::sort(results.begin(), results.end(), + ecell4::utils::pair_second_element_comparator()); + + SGFRD_TRACE(tracer_.write(""results are sorted"")) + return results; + } + + std::vector > + burst_and_shrink_non_multis(const VertexID& vid, + const std::vector >& intruders) + { + SGFRD_SCOPE(us, burst_and_shrink_non_multis_vertex, tracer_) + const std::pair vpos = std::make_pair( + polygon().position_at(vid), vid); + + const Real tm(this->time()); + std::vector > results; + + DomainID did; Real dist; + for(const auto& didd : intruders) + { + SGFRD_SCOPE(ns, loop_for_intruders, tracer_) + std::tie(did, dist) = didd; + + const auto& ev = get_event(did); + if(ev->which_domain() == event_type::multi_domain) + { + SGFRD_TRACE(tracer_.write(""domain %1% is multi"", did)) + results.push_back(std::make_pair(did, dist)); + continue; + } + SGFRD_TRACE(tracer_.write(""domain %1% is not a multi"", did)) + + DomainID did_; ParticleID pid_; Particle p_; FaceID fid_; + for(const auto& pidpf : burst_event(std::make_pair(did, ev), tm)) + { + std::tie(pid_, p_, fid_) = pidpf; + SGFRD_TRACE(tracer_.write( + ""add closely-fitted domain to bursted particle %1%"", pid_)) + + did_ = add_event(create_tight_domain( + create_tight_shell(pid_, p_, fid_), pid_, p_)); + + const auto dist = ecell4::polygon::distance(this->polygon(), + vpos, std::make_pair(p_.position(), fid_)); + + const auto min_shell_rad = + calc_min_single_circular_shell_radius(p_) * + single_circular_shell_factor; + + results.emplace_back(did_, dist - min_shell_rad); + } + remove_event(did); + SGFRD_TRACE(tracer_.write(""domain %1% is bursted and shrinked"", did)) + } + + std::sort(results.begin(), results.end(), + ecell4::utils::pair_second_element_comparator()); + SGFRD_TRACE(tracer_.write(""results are sorted"")) + return results; + } + + + // to clear volume. burst all the overlapping shells then add closely-fitted + // shells to them. returns true if there are no overlapping particles. + bool burst_and_shrink_overlaps( + const Particle& p, const FaceID& fid, const DomainID& did); + + // form multi shell recursively + DomainID form_multi(const ParticleID& pid, const Particle& p, const FaceID& fid, + const std::vector >& doms); + + // search intruder for multi, burst them and add them to multi if needed. + void add_to_multi_recursive(Multi&); + + void merge_multi(Multi& from, Multi& to) + { + SGFRD_SCOPE(us, merge_multi, tracer_) + + const auto id_of_from = get_domain_id(from); + remove_event(id_of_from); + SGFRD_TRACE(tracer_.write(""remove domain from(%1%)"", id_of_from)) + + // reset domain_id + const domain_id_setter didset(this->get_domain_id(to)); + mut_sh_vis_applier(didset, from); + SGFRD_TRACE(tracer_.write(""set domain ID for shell in from(%1%)"", id_of_from)) + + + // move particle + ParticleID pid; Particle p; + for(const auto& pidp : from.particles()) + { + std::tie(pid, p) = pidp; + const bool addp_result = to.add_particle(pid); + assert(addp_result); + } + // move shell + for(const ShellID& sid : from.shell_ids()) + { + const bool adds_result = to.add_shell(sid); + SGFRD_TRACE(tracer_.write(""Shell(%1%).domain_id = %2%"", sid, + boost::get(this->get_shell(sid)).domain_id())) + assert(adds_result); + } + to.determine_parameters(); + + SGFRD_TRACE(tracer_.write(""multi domain %1% is removed"", id_of_from)) + return; + } + + struct volume_clearer + { + volume_clearer(domain_id_type d, const Multi& dom, SGFRDSimulator& s, + immutable_shell_visitor_applier_type& imm) + : sim(s), did(d), domain(dom), applier(imm) + {} + + bool operator()(const Particle& p, const FaceID& fid) + { + SGFRD_SCOPE(us, volume_clearer, sim.tracer_) + SGFRD_TRACE(sim.tracer_.write(""ignoring nothing"")) + + this->escaped_ = false; + inside_checker is_inside(p.position(), p.radius(), fid, sim.polygon()); + if(applier(is_inside, domain)) + { + SGFRD_TRACE(sim.tracer_.write(""particle is inside of the shell"")) + return true; + } + SGFRD_TRACE(sim.tracer_.write(""particle escaped. checking overlapping..."")); + + const bool no_overlap = sim.burst_and_shrink_overlaps(p, fid, did); + escaped_ = no_overlap; + SGFRD_TRACE(sim.tracer_.write(""no_overlap = %1%"", no_overlap)); + return no_overlap; + } + bool operator()(const Particle& p, const FaceID& fid, + const ParticleID& ignore) + { + SGFRD_SCOPE(us, volume_clearer, sim.tracer_) + SGFRD_TRACE(sim.tracer_.write(""ignoring %1%"", ignore)) + + escaped_ = false; + inside_checker is_inside(p.position(), p.radius(), fid, sim.polygon()); + if(applier(is_inside, domain)) + { + SGFRD_TRACE(sim.tracer_.write(""particle is inside of the shell"")) + return true; + } + SGFRD_TRACE(sim.tracer_.write(""particle escaped. checking overlapping..."")); + + const bool no_overlap = sim.burst_and_shrink_overlaps(p, fid, did); + escaped_ = no_overlap; + SGFRD_TRACE(sim.tracer_.write(""no_overlap = %1%"", no_overlap)); + return no_overlap; + } + bool operator()(const Particle& p, const FaceID& fid, + const ParticleID& ignore1, const ParticleID& ignore2) + { + SGFRD_SCOPE(us, volume_clearer, sim.tracer_) + SGFRD_TRACE(sim.tracer_.write(""ignoring %1% and %2%"", ignore1, ignore2)) + + escaped_ = false; + inside_checker is_inside(p.position(), p.radius(), fid, sim.polygon()); + if(applier(is_inside, domain)) + { + SGFRD_TRACE(sim.tracer_.write(""particle is inside of the shell"")) + return true; + } + SGFRD_TRACE(sim.tracer_.write(""particle escaped. checking overlapping..."")); + + const bool no_overlap = sim.burst_and_shrink_overlaps(p, fid, did); + escaped_ = no_overlap; + SGFRD_TRACE(sim.tracer_.write(""no_overlap = %1%"", no_overlap)); + return no_overlap; + } + + bool escaped() const {return escaped_;} + + tracer& access_tracer() + { + return sim.tracer_; + } + + private: + bool escaped_; + SGFRDSimulator& sim; + domain_id_type did; + Multi const& domain; + immutable_shell_visitor_applier_type applier; + }; + +//----------------------------------- event ------------------------------------ + + //! make event from domain and push it into scheduler + template + DomainID add_event(const domainT& dom) + { + SGFRD_SCOPE(ns, add_event, tracer_); + SGFRD_TRACE(tracer_.write(""the domain has dt = %1%, begin_time = %2%"", + dom.dt(), dom.begin_time())) + + auto ev = std::make_shared(dom.begin_time() + dom.dt(), dom); + const DomainID did = scheduler_.add(ev); + + SGFRD_TRACE(tracer_.write(""event_time = %1%, domain ID = %2%"", ev->time(), did)) + + domain_id_setter didset(did); + mut_sh_vis_applier(didset, dom); + return did; + } + + // assuming the event is already poped + void fire_event(event_id_pair_type ev) + { + SGFRD_SCOPE(us, fire_event, tracer_); + SGFRD_TRACE(tracer_.write(""event %1% fired"", ev.first)) + + SGFRDEvent::domain_type& dom = ev.second->domain(); + + switch(ev.second->which_domain()) + { + case event_type::single_domain: + { + return this->fire_single(boost::get(dom), ev.first); + } + case event_type::pair_domain: + { + STAT(stat_fired_events.add_count(FirePair);) + return this->fire_pair(boost::get(dom), ev.first); + } + case event_type::multi_domain: + { + STAT(stat_fired_events.add_count(FireMulti);) + return this->fire_multi(boost::get(dom), ev.first); + } + case event_type::birth_domain: + { + STAT(stat_fired_events.add_count(FireBirth);) + return this->fire_birth(boost::get(dom), ev.first); + } + default: + { + throw std::runtime_error((boost::format( + ""event::which_domain returns invalid value (%1%)"") % + ev.second->which_domain()).str()); + } + } + } + + // assuming the event is already poped + bursted_type burst_event(const event_id_pair_type& ev, Real tm) + { + SGFRD_SCOPE(us, burst_event, tracer_); + SGFRDEvent::domain_type& dom = ev.second->domain(); + + switch(ev.second->which_domain()) + { + case event_type::single_domain: + { + return this->burst_single(boost::get(dom), tm); + } + case event_type::pair_domain: + { + return this->burst_pair(boost::get(dom), tm); + } + case event_type::multi_domain: + { + return this->burst_multi(boost::get(dom), tm); + } + case event_type::birth_domain: + { + // birth domain have nothing inside and particle appears only + // when the domain is fired. Thus when it is bursted, nothing + // happens. + return {}; + } + default: + { + throw std::runtime_error((boost::format( + ""event::which_domain returns invalid value (%1%)"") % + ev.second->which_domain()).str()); + } + } + } + + ShellID create_tight_shell( + const ParticleID& pid, const Particle& p, const FaceID fid) + { + SGFRD_SCOPE(us, create_tight_shell, tracer_); + SGFRD_TRACE(tracer_.write(""add close shell for %1% @ face %2%"", pid, fid)) + SGFRD_TRACE(tracer_.write(""species %1% has radius %2%"", + p.species_serial(), p.radius())) + + const ShellID sid(shell_id_gen()); + circular_shell_type sh(circle_type(p.radius(), p.position(), + this->polygon().triangle_at(fid).normal()), fid); + SGFRD_TRACE(tracer_.write(""shell has size == %1%"", sh.size())) + + shell_container_.check_add_shell(sid, sh, fid, ""create tight shell""); + SGFRD_TRACE(tracer_.write(""new shell id is %1%"", sid)) + return sid; + } + Single create_tight_domain( + const ShellID& sid, const ParticleID& pid, const Particle& p) + { + SGFRD_SCOPE(us, create_tight_domain, tracer_); + SGFRD_TRACE(tracer_.write(""for particle %1%, shell %2%"", pid, sid)) + return Single(Single::ESCAPE, 0., this->time(), sid, std::make_pair(pid, p)); + } + + std::pair + create_minimum_single_shell( + const ParticleID& pid, const Particle& p, const FaceID fid) + { + // this function is used to create shells for multi. + // multi domain allows its shells to overlap each other. + return create_single_circular_shell(std::make_pair(p.position(), fid), + calc_min_single_circular_shell_radius(p), false); + } + + Multi create_empty_multi() + { + return Multi(*this, *(this->world_), this->time(), + this->bd_dt_factor_, this->reaction_length_); + } + + //! make domain and call add_event + DomainID create_event(const ParticleID&, const Particle&, const FaceID); + + expected > > + form_single_circular_event( + const ParticleID&, const Particle&, const FaceID, const Real); + + expected > > + form_single_conical_event( + const ParticleID&, const Particle&, const FaceID); + + boost::optional + form_pair(const ParticleID& pid, const Particle& p, const FaceID& fid, + const std::vector >& intruders); + + + std::vector > + get_intrusive_vertices(const std::pair& pos, + const Real radius) const + { + return this->world_->list_vertices_within_radius(pos, radius); + } + + // the second value is distance between + // the point `pos` and the surface of a domain + std::vector> + get_intrusive_domains(const std::pair& pos, + const Real radius) const + { + SGFRD_SCOPE(us, get_intrusive_domains_position, tracer_); + + const auto shells(shell_container_.list_shells_within_radius(pos, radius)); + + SGFRD_TRACE(tracer_.write(""collected %1% shells in radius %2%"", + shells.size(), radius)); + + std::vector> domains; + domains.reserve(shells.size()); + for(const auto& shid_sh : shells) + { + const auto& shell_id_pair = shid_sh.first; + const auto dist = shid_sh.second; + + SGFRD_TRACE(tracer_.write(""shell %1% = {%2%} is at %3% distant"", + shell_id_pair.first, shell_id_pair.second, dist)); + + const DomainID did = boost::apply_visitor( + domain_id_getter(), shell_id_pair.second); + + SGFRD_TRACE(tracer_.write(""shell %1% is related to domain %2%"", + shell_id_pair.first, did)); + + // filter by domainID to be unique + auto found = std::find_if(domains.begin(), domains.end(), + [did](const std::pair& did_dist) noexcept -> bool { + return did_dist.first == did; + }); + if(found == domains.end()) + { + SGFRD_TRACE(tracer_.write(""domain %1% is assigned to retval"", did)); + domains.emplace_back(did, dist); + } + else + { + // choose the nearer one from the domain that contains multiple + // shells. + found->second = std::min(found->second, dist); + SGFRD_TRACE(tracer_.write(""domain %1% is already assigned"", did)); + } + } + for(std::size_t i=0; i < domains.size(); ++i) + { + SGFRD_TRACE(tracer_.write(""%1%, "", domains.at(i).first)); + } + + std::sort(domains.begin(), domains.end(), + utils::pair_second_element_comparator()); + return domains; + } + + std::vector > + get_intrusive_domains(const VertexID& vid, const Real radius) const + { + SGFRD_SCOPE(us, get_intrusive_domains_vid, tracer_); + + const std::pair vpos(polygon().position_at(vid), vid); + const std::vector, Real> + > shells(shell_container_.list_shells_within_radius(vpos, radius)); + + SGFRD_TRACE(tracer_.write(""collected %1% shells in radius %2%"", + shells.size(), radius)); + + std::vector > domains; + domains.reserve(shells.size()); + + for(std::vector, Real> + >::const_iterator iter(shells.begin()), iend(shells.end()); + iter != iend; ++iter) + { + std::pair shell_id_pair; + Real dist; + std::tie(shell_id_pair, dist) = *iter; + SGFRD_TRACE(tracer_.write(""shell %1% = {%2%} is at %3% distant"", + shell_id_pair.first, shell_id_pair.second, dist)); + + const DomainID did = boost::apply_visitor( + domain_id_getter(), shell_id_pair.second); + + SGFRD_TRACE(tracer_.write(""shell %1% is related to domain %2%"", + shell_id_pair.first, did)); + + std::vector >::iterator found = + std::find_if(domains.begin(), domains.end(), + ecell4::utils::pair_first_element_unary_predicator< + DomainID, Real>(did)); + if(found == domains.end()) + { + SGFRD_TRACE(tracer_.write(""domain %1% is assigned to retval"", did)); + domains.push_back(std::make_pair(did, dist)); + } + else + { + found->second = std::min(found->second, dist); + SGFRD_TRACE(tracer_.write(""domain %1% is already assigned"", did)); + for(std::size_t i=0; i < domains.size(); ++i) + { + SGFRD_TRACE(tracer_.write(""%1%, "", domains.at(i).first)); + } + } + } + std::sort(domains.begin(), domains.end(), + utils::pair_second_element_comparator()); + + return domains; + } + + //! just a geometric restriction + Real get_max_circle_size(const std::pair& pos) const + { + SGFRD_SCOPE(us, get_max_circle_size, tracer_); + SGFRD_TRACE(tracer_.write(""position = %1%, %2%"", pos.first, pos.second)); + + Real lensq = std::numeric_limits::max(); + for(const auto& barrier : world_->barrier_at(pos.second)) + { + const Real dist2 = ecell4::sgfrd::distance_sq(pos.first, barrier); + if(dist2 < lensq) + { + lensq = dist2; + } + } + SGFRD_TRACE(tracer_.write(""distance to barrier = %1%"", std::sqrt(lensq))); + return std::sqrt(lensq); + } + Real get_max_cone_size(const VertexID& vid) const + { + Real min_len = std::numeric_limits::max(); + for(const auto eid : this->polygon().outgoing_edges(vid)) + { + min_len = std::min(min_len, this->polygon().length_of(eid)); + } + return min_len * 0.5; + } + + Real calc_min_single_circular_shell_radius(const Particle& p) const + { + return p.radius() * single_circular_shell_factor; + } + Real calc_min_single_conical_shell_radius(const Particle& p) const + { + return p.radius() * single_conical_surface_shell_factor; + } + + Real calc_k_tot(const std::vector& rules) const + { + SGFRD_SCOPE(ns, calc_k_tot, tracer_) + Real k_tot = 0; + for(const auto& rule : rules) + { + SGFRD_TRACE(tracer_.write(""reaction rule found: k = %1%"", rule.k())); + k_tot += rule.k(); + } + return k_tot; + } + + Real draw_reaction_time(const Real k_tot) + { + SGFRD_SCOPE(ns, draw_reaction_time, tracer_) + SGFRD_TRACE(tracer_.write(""for ktot = %1%"", k_tot)); + + if(k_tot <= 0){return std::numeric_limits::infinity();} + if(k_tot == std::numeric_limits::infinity()){return 0;} + + const Real rnd = this->uniform_real(); + SGFRD_TRACE(tracer_.write(""rnd = %1%"", rnd)); + if(rnd <= 0){return std::numeric_limits::infinity();} + + SGFRD_TRACE(tracer_.write(""reaction occurs in a finite time"")); + + return (1. / k_tot) * (-std::log(rnd)); + } + + ReactionRule const& + determine_reaction_rule(const std::vector& rules) + { + if(rules.size() == 1){return rules.front();} + if(rules.empty()) + { + throw std::invalid_argument(""no reaction rule exists""); + } + + const Real ktot = calc_k_tot(rules); + const Real thrs = ktot * this->uniform_real(); + Real a = 0.0; + for(const auto& rule : rules) + { + a += rule.k(); + if(a > thrs) return rule; + } + throw std::logic_error(""reaction cannot detemined""); + } + + // for BD part... + Real3 random_circular_uniform(const Real r, const FaceID& fid) + { + SGFRD_SCOPE(ns, sgfrd_random_circular_uniform, tracer_); + + const Real theta = this->rng_.uniform(0., 2 * M_PI); + SGFRD_TRACE(tracer_.write(""theta = %1%"", theta)); + + const Real3 rnd(r * std::cos(theta), r * std::sin(theta), 0.); + SGFRD_TRACE(tracer_.write(""random displacement = %1%"", rnd)); + + const Real3& normal = this->polygon().triangle_at(fid).normal(); + SGFRD_TRACE(tracer_.write(""normal vector on face(%1%) = %2%"", fid, normal)); + + const Real tilt = calc_angle(Real3(0, 0, 1), normal); + SGFRD_TRACE(tracer_.write(""tilt angle = %1%"", tilt)); + + if (std::abs(tilt) < 1e-10) {return rnd;} + else if(std::abs(tilt - M_PI) < 1e-10) {return rnd * (-1.0);} + else if(std::abs(tilt + M_PI) < 1e-10) {return rnd * (-1.0);} + + SGFRD_TRACE(tracer_.write(""tilt angle is not 0 or +-pi. rotating..."")); + + const Real3 axis = cross_product(Real3(0., 0., 1.), normal); + return rotate(tilt, axis * (1. / length(axis)), rnd); + } + + static Real calc_modest_shell_size( + const Particle& p, const Particle& nearest, const Real dist) + { + // here, `dist` means the distance between shell surfaces. + // so the following relationship should be satisfied. + // >> p.radius() + nearest.radius() + dist == + // >> distance_on_polygon(p.position(), nearest.position()) + + // However, this function does not take the face information, + // we cannot calculate the distance between p and nearest. + assert(0.0 <= dist); + + const Real D1 = p.D(); + const Real D2 = nearest.D(); + assert(!(D1 == 0.0 && D2 == 0.0)); + const Real r1 = p.radius(); + const Real sqrtD1 = std::sqrt(D1); + const Real sqrtD2 = std::sqrt(D2); + return sqrtD1 / (sqrtD1 + sqrtD2) * dist + r1; + } + + private: + + static const Real single_circular_shell_factor; + static const Real single_circular_shell_mergin; + static const Real single_conical_surface_shell_factor; + static const Real single_conical_surface_shell_mergin; + static const Real minimum_separation_factor; + + private: + + // from SimulatorBase + // std::shared_ptr model_; + // std::shared_ptr world_; + // Integer num_steps_; + bool is_dirty_; + Real dt_; + Real bd_dt_factor_; + Real reaction_length_; + ecell4::RandomNumberGenerator& rng_; + scheduler_type scheduler_; + shell_id_generator_type shell_id_gen; + shell_container_type shell_container_; + mutable_shell_visitor_applier_type mut_sh_vis_applier; + immutable_shell_visitor_applier_type imm_sh_vis_applier; + std::vector > last_reactions_; + mutable tracer tracer_; + + public: + STAT(mutable statistics stat_reaction_condition;) + STAT(mutable statistics stat_multi_reason;) + STAT(mutable statistics stat_fired_events;) + STAT(mutable statistics stat_multi_size;) +}; + + +} // sgfrd +} // ecell4 +#endif // ECELL4_SGFRD_SIMULATOR +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/ShellID.hpp",".hpp","1065","48","#ifndef ECELL4_SGFRD_SHELL_ID +#define ECELL4_SGFRD_SHELL_ID +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ +struct ShellID: public ecell4::Identifier +{ + typedef ecell4::Identifier base_type; + + ShellID(value_type const& value = value_type(0, 0)) + : base_type(value) {} +}; + +template +inline std::basic_ostream& +operator<<(std::basic_ostream& strm, const ShellID& v) +{ + strm << ""ShellID("" << v().first << "":"" << v().second << "")""; + return strm; +} + +} // sgfrd +} // ecell4 + +namespace std { + +template<> +struct hash +{ + typedef std::size_t result_type; + typedef ecell4::sgfrd::ShellID argument_type; + + result_type operator()(argument_type const& val) const + { + return static_cast(val().first ^ val().second); + } +}; + +} // std + +#endif /* ECELL4_SGFRD_SHELL_ID */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/ShellContainer.hpp",".hpp","17738","530","#ifndef ECELL4_SGFRD_SHELL_CONTAINER +#define ECELL4_SGFRD_SHELL_CONTAINER +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class ShellContainer +{ +public: + + typedef ::ecell4::Polygon polygon_type; + + typedef ecell4::Circle circle_type; + typedef ecell4::ConicalSurface conical_surface_type; + typedef Shell circular_shell_type; + typedef Shell conical_surface_shell_type; + + static const int circular_shell = 0; + static const int conical_shell = 1; + typedef boost::variant< + circular_shell_type, // <- 0 + conical_surface_shell_type // <- 1 + > storage_type; + typedef storage_type shell_type; + typedef std::pair shell_id_pair_type; + typedef std::vector container_type; + typedef std::unordered_map + shell_id_to_index_map_type; + + typedef StructureRegistrator face_registrator_type; + typedef StructureRegistrator vertex_registrator_type; + + struct face_register_updater; + struct vertex_register_updater; + struct register_cleaner; + +public: + + ShellContainer(const std::shared_ptr& poly) + : polygon_(poly) + {} + ~ShellContainer(){} + + template + void add_shell(const ShellID& id, const shellT& sh, const FaceID& fid); + template + void add_shell(const ShellID& id, const shellT& sh, const VertexID& vid); + + // add a shell, with overlap checking. + // Generally, it cannot be performed because Multi allows its shells to + // overlap each other. These functions are for Single/Pair cases only. + template + void check_add_shell(const ShellID& id, const shellT& sh, const FaceID& fid, + const std::string& context); + template + void check_add_shell(const ShellID& id, const shellT& sh, const VertexID& vid, + const std::string& context); + + template + void update_shell(const ShellID& id, const shellT& sh, + const FaceID& fid); + template + void update_shell(const ShellID& id, const shellT& sh, + const VertexID& vid); + + storage_type const& get_shell(const ShellID& id) const noexcept + { + return container_.at(shell_id_to_index_map_.find(id)->second).second; + } + storage_type& get_shell(const ShellID& id) noexcept + { + return container_.at(shell_id_to_index_map_[id]).second; + } + + void remove_shell(const ShellID& shid); + + std::vector const& list_shells_on(const FaceID& fid) const noexcept + { + return face_registrator_.elements_over(fid); + } + std::vector const& list_shells_on(const VertexID& vid) const noexcept + { + return vertex_registrator_.elements_over(vid); + } + + std::size_t num_shells() const {return container_.size();} + + // calculate distance as 3D object + std::vector, Real>> + list_shells_within_radius(const Real3& pos, const Real radius) const + { + return list_shells_within_radius_impl(pos, radius, + [](const ShellID&) noexcept -> bool {return false;}); + } + std::vector, Real>> + list_shells_within_radius(const Real3& pos, const Real radius, + const ShellID& ignore) const + { + return list_shells_within_radius_impl(pos, radius, + [ignore](const ShellID& shid) noexcept -> bool { + return shid == ignore; + }); + } + std::vector, Real>> + list_shells_within_radius(const Real3& pos, const Real radius, + const ShellID& ignore1, + const ShellID& ignore2) const + { + return this->list_shells_within_radius_impl(pos, radius, + [ignore1, ignore2](const ShellID& shid) noexcept -> bool { + return shid == ignore1 || shid == ignore2; + }); + } + + // calculate distance along the polygon. + template + std::vector, Real>> + list_shells_within_radius(const std::pair& pos, + const Real radius) const + { + return this->list_shells_within_radius_impl(pos, radius, + [](const ShellID&) noexcept -> bool {return false;}); + } + template + std::vector, Real>> + list_shells_within_radius(const std::pair& pos, + const Real radius, const ShellID& ignore) const + { + return this->list_shells_within_radius_impl(pos, radius, + [ignore](const ShellID& shid) noexcept -> bool { + return shid == ignore; + }); + } + template + std::vector, Real>> + list_shells_within_radius(const std::pair& pos, + const Real radius, const ShellID& ignore1, + const ShellID& ignore2) const + { + return this->list_shells_within_radius_impl(pos, radius, + [ignore1, ignore2](const ShellID& shid) noexcept -> bool { + return shid == ignore1 || shid == ignore2; + }); + } + + std::vector list_shells() const {return container_;} + +private: + + template + std::vector, Real>> + list_shells_within_radius_impl(const std::pair& pos, + const Real radius, F ignore) const; + + // 3D version + template + std::vector, Real>> + list_shells_within_radius_impl(const Real3& pos, + const Real radius, F ignore) const; + +private: + + std::shared_ptr polygon_; + container_type container_; + shell_id_to_index_map_type shell_id_to_index_map_; + face_registrator_type face_registrator_; + vertex_registrator_type vertex_registrator_; +}; + +struct ShellContainer::register_cleaner + : public boost::static_visitor +{ + ShellContainer& scon; + ShellID sid; + + register_cleaner(ShellContainer& self, const ShellID& si) + : scon(self), sid(si){} + + template + void operator()(const Shell& sh) const + { + scon.face_registrator_.remove(sid); + return; + } + + template + void operator()(const Shell& sh) const + { + scon.vertex_registrator_.remove(sid); + return; + } +}; + +struct ShellContainer::face_register_updater + : public boost::static_visitor +{ + ShellContainer& scon; + ShellID sid; + FaceID fid; + + face_register_updater(ShellContainer& self, ShellID s, FaceID f) + : scon(self), sid(s), fid(f) + {} + + template + void operator()(const Shell& sh) const + { + scon.face_registrator_.update(sid, fid); + return; + } + + template + void operator()(const Shell& sh) const + { + scon.vertex_registrator_.remove(sid, sh.structure_id()); + scon.face_registrator_.emplace(sid, fid); + return; + } +}; + +struct ShellContainer::vertex_register_updater + : public boost::static_visitor +{ + ShellContainer& scon; + ShellID sid; + VertexID vid; + + vertex_register_updater(ShellContainer& self, ShellID s, VertexID v) + : scon(self), sid(s), vid(v) + {} + + template + void operator()(const Shell& sh) const + { + scon.face_registrator_.remove(sid, sh.structure_id()); + scon.vertex_registrator_.emplace(sid, vid); + return; + } + + template + void operator()(const Shell& sh) const + { + scon.vertex_registrator_.update(sid, vid); + return; + } +}; + +inline void ShellContainer::remove_shell(const ShellID& shid) +{ + if(shell_id_to_index_map_.count(shid) == 0) + { + throw std::invalid_argument(""shellcontianer doesnt have the shell""); + } + + const std::size_t idx = shell_id_to_index_map_[shid]; + boost::apply_visitor(register_cleaner(*this, shid), + container_.at(idx).second); + + container_.at(idx) = container_.back(); + shell_id_to_index_map_[container_.back().first] = idx; + container_.pop_back(); + return ; +} + + +template +void ShellContainer::add_shell( + const ShellID& id, const shellT& sh, const FaceID& fid) +{ + if(shell_id_to_index_map_.count(id) == 1) + { + throw std::invalid_argument(""shellcontianer already have the shell""); + } + + const std::size_t idx = container_.size(); + shell_id_to_index_map_[id] = idx; + face_registrator_.emplace(id, fid); + container_.push_back(std::make_pair(id, storage_type(sh))); + return; +} + +template +void ShellContainer::add_shell( + const ShellID& id, const shellT& sh, const VertexID& vid) +{ + if(shell_id_to_index_map_.count(id) == 1) + { + throw std::invalid_argument(""shellcontianer already have the shell""); + } + const std::size_t idx = container_.size(); + shell_id_to_index_map_[id] = idx; + vertex_registrator_.emplace(id, vid); + container_.push_back(std::make_pair(id, storage_type(sh))); + return; +} + + +template +void ShellContainer::check_add_shell( + const ShellID& id, const shellT& sh, const FaceID& fid, + const std::string& context) +{ + if(shell_id_to_index_map_.count(id) == 1) + { + throw std::invalid_argument(""shellcontianer already have the shell""); + } + + /* overlap check */ { + std::vector, Real> + > ovlp = this->list_shells_within_radius( + std::make_pair(sh.position(), fid), sh.size()); + if(!ovlp.empty()) + { + std::cerr << ""WARNING: circular shells overlap!\n""; + std::cerr << ""context: "" << context << '\n'; + for(const auto& ov: ovlp) + { + std::cerr << "" : shell "" << ov.first.first << "" at "" + << ov.second - sh.size() << ""distant.\n""; + } + std::cerr << std::flush; + } + } + + const std::size_t idx = container_.size(); + shell_id_to_index_map_[id] = idx; + face_registrator_.emplace(id, fid); + container_.push_back(std::make_pair(id, storage_type(sh))); + return; +} + +template +void ShellContainer::check_add_shell( + const ShellID& id, const shellT& sh, const VertexID& vid, + const std::string& context) +{ + if(shell_id_to_index_map_.count(id) == 1) + { + throw std::invalid_argument(""shellcontianer already have the shell""); + } + + /* overlap check */{ + std::vector, Real> + > ovlp = this->list_shells_within_radius( + std::make_pair(sh.position(), vid), sh.size()); + if(!ovlp.empty()) + { + std::cerr << ""WARNING: conical shells overlap!\n""; + std::cerr << ""context: "" << context << '\n'; + for(const auto& ov: ovlp) + { + std::cerr << "" : shell "" << ov.first.first << "" at "" + << ov.second << ""distant.\n""; + } + std::cerr << std::flush; + } + } + + const std::size_t idx = container_.size(); + shell_id_to_index_map_[id] = idx; + vertex_registrator_.emplace(id, vid); + container_.push_back(std::make_pair(id, storage_type(sh))); + return; +} + + +template +void ShellContainer::update_shell( + const ShellID& id, const shellT& sh, const FaceID& fid) +{ + if(shell_id_to_index_map_.count(id) == 0) + { + throw std::invalid_argument(""shellcontianer doesnt have the shell""); + } + + const std::size_t idx = shell_id_to_index_map_[id]; + boost::apply_visitor(face_register_updater(*this, id, fid), + container_.at(idx).second); + container_.at(idx).second = sh; + return; +} + +template +void ShellContainer::update_shell( + const ShellID& id, const shellT& sh, const VertexID& vid) +{ + if(shell_id_to_index_map_.count(id) == 0) + { + throw std::invalid_argument(""shellcontianer doesnt have the shell""); + } + + const std::size_t idx = shell_id_to_index_map_[id]; + boost::apply_visitor(vertex_register_updater(*this, id, vid), + container_.at(idx).second); + container_.at(idx).second = sh; + return; +} + +template +std::vector, Real>> +ShellContainer::list_shells_within_radius_impl( + const Real3& pos, const Real radius, F ignore) const +{ + throw NotSupported( + ""sGFRD does not support list_shells_within_radius in 3D space""); +// //XXX need more sophisticated way than brute-force searching +// std::vector, Real>> retval; +// const distance_calculator distance(pos); +// for(const auto& shp : this->container_) +// { +// const auto& shid = shp.first; +// const auto& shell = shp.second; +// if(ignore(shid)) {continue;} +// +// const Real dist = boost::apply_visitor(distance, shell); +// if(dist < radius) +// { +// retval.emplace_back(shp, dist); +// } +// } +// std::sort(retval.begin(), retval.end(), +// ecell4::utils::pair_second_element_comparator< +// std::pair, Real>()); +// return retval; +} + +template +std::vector, Real>> +ShellContainer::list_shells_within_radius_impl( + const std::pair& pos, const Real radius, F ignore) const +{ + std::vector, Real>> retval; + const distance_calculator_on_surface distance_on_surf(pos, *polygon_); + + // check shells on the same position (either face or vertex) + for(const ShellID& shid : list_shells_on(pos.second)) + { + if(ignore(shid)) {continue;} + + const auto& shell = this->get_shell(shid); + const Real dist = boost::apply_visitor(distance_on_surf, shell); + if(dist < radius) + { + retval.emplace_back(std::make_pair(shid, shell), dist); + } + } + + const auto neighbor_faces = polygon_->neighbor_faces_of (pos.second); + const auto neighbor_vtxs = polygon_->neighbor_vertices_of(pos.second); + + // check shells on the neighboring faces + for(const FaceID& fid : neighbor_faces) + { + for(const ShellID& shid : list_shells_on(fid)) + { + if(ignore(shid)) {continue;} + + const auto& shell = this->get_shell(shid); + const Real dist = boost::apply_visitor(distance_on_surf, shell); + if(dist < radius) + { + retval.emplace_back(std::make_pair(shid, shell), dist); + } + } + } + // check shells on the neighboring vertices + for(const VertexID& vid : neighbor_vtxs) + { + for(const ShellID& shid : list_shells_on(vid)) + { + if(ignore(shid)) {continue;} + + const auto& shell = this->get_shell(shid); + const Real dist = boost::apply_visitor(distance_on_surf, shell); + if(dist < radius) + { + retval.emplace_back(std::make_pair(shid, shell), dist); + } + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + + // ----------------------------------------------------------------------- + // check double count. + // neighbor_faces and neighbor_vtxs should not contain pos.second itself. + // So if the polygon is okay, there will not be overlap in retval. + + std::set shellids; + for(const auto& found : retval) + { + const auto& shid = found.first.first; + if(shellids.count(shid) != 0) + { + std::ostringstream oss; + oss << ""Error: broken Polygon: Shell "" << shid << "" found twice.\n""; + oss << ""neighboring faces of "" << pos.second << "" are""; + for(const FaceID& fid : neighbor_faces) + { + oss << "", "" << fid; + } + oss << "".\n""; + oss << ""neighboring vertices of "" << pos.second << "" are""; + for(const VertexID& vid : neighbor_vtxs) + { + oss << "", "" << vid; + } + oss << "".\n""; + face_registrator_ .dump(std::cerr); + vertex_registrator_.dump(std::cerr); + throw std::runtime_error(oss.str()); + } + shellids.insert(found.first.first); + } + return retval; +} + +}// sgfrd +}// ecell4 +#endif// ECELL4_SGFRD_SHELL_CONTAINER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/SGFRDWorld.cpp",".cpp","15404","440","#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +std::pair, bool> +SGFRDWorld::new_particle(const Particle& p) +{ + if(const auto pfid = this->find_face(p.position())) + { + Particle p_(p); + p_.position() = pfid->first; + return this->new_particle(p_, pfid->second); + } + throw std::invalid_argument(""[error] SGFRDWorld::new_particle: "" + ""particle locates distant from polygon""); +} + +std::pair, bool> +SGFRDWorld::new_particle(const Particle& p, const FaceID& fid) +{ + if(p.radius() > this->estimated_possible_largest_particle_radius_) + { + throw NotSupported(""[error] Particle size exceeds the estimated limit. "" + ""particle size must be smaller than the width of triangles""); + } + + const ParticleID pid = pidgen_(); + // now this consider only 2D particles + const auto overlap2d(list_particles_within_radius( + std::make_pair(p.position(), fid), p.radius())); + + if(!overlap2d.empty()) + { +// std::cout << ""overlapped particle = {""; +// std::cout << '{' << overlap2d.front().first.first +// << "", distance = "" << overlap2d.front().second << '}'; +// for(std::size_t i=1; i, bool> +SGFRDWorld::throw_in_particle(const Species& sp) +{ + const auto info = this->get_molecule_info(sp); + + Real3 pos; FaceID fid; + pos = this->polygon_->draw_position(this->rng_, fid); + const Particle p(sp, pos, info.radius, info.D); + return this->new_particle(p, fid); +} + +void SGFRDWorld::add_molecules(const Species& sp, const Integer& num) +{ + if (num < 0) + { + throw std::invalid_argument(""The number of molecules must be positive.""); + } + for(Integer i=0; ithrow_in_particle(sp).second == false) + { + /*do nothing*/ + } + } + return; +} + +void SGFRDWorld::add_molecules(const Species& sp, const Integer& num, + const std::shared_ptr shape) +{ + if (num < 0) + { + throw std::invalid_argument(""The number of molecules must be positive.""); + } + else if (num == 0) + { + return; + } + + // XXX: this implementation is not only inefficient, but also unsafe because + // it may not stop. Since `shape` is a base class, here the concrete + // representation of a shape cannot be obtained (except dynamic_cast). + // There is no way to predict the precise area of the overlapped + // region. If the overlapped region is just a point or a line without + // area, no particle can be inside it. If the overlapped region is too + // small to place `num` number of particles, it also does not finish. + // But still some faces overlap with the shape, and there is no way to + // make it sure that this function never ends, we need to continue + // searching. + + const auto& width = this->edge_lengths(); + const auto transpose_direction = [&width](const Triangle& triangle) + noexcept -> boost::container::static_vector { + const auto& v1 = triangle.vertices()[0]; + const auto& v2 = triangle.vertices()[1]; + const auto& v3 = triangle.vertices()[2]; + + boost::container::static_vector retval; + for(std::size_t i=0; i<3; ++i) + { + Real3 disp(0.0, 0.0, 0.0); + if(v1[i] < 0.0 || v2[i] < 0.0 || v3[i] < 0.0) + { + disp[i] = width[i]; + retval.push_back(disp); + } + else if(v1[i] >= width[i] || v2[i] >= width[i] || v3[i] >= width[i]) + { + disp[i] = -width[i]; + retval.push_back(disp); + } + } + return retval; + }; + + std::vector potentially_overlapping_fids; + + for(auto&& fid : this->polygon_->list_face_ids()) + { + const auto& triangle = this->polygon_->triangle_at(fid); + + Real3 lower(0,0,0), upper(width); + triangle.bounding_box(width, lower, upper); + + if(shape->test_AABB(lower, upper)) + { + potentially_overlapping_fids.push_back(fid); + continue; + } + + const auto transposes = transpose_direction(triangle); + for(const auto& transpose : transposes) + { + auto vertices = triangle.vertices(); + for(auto& vertex : vertices) + { + vertex += transpose; + } + const Triangle transposed(vertices); + + transposed.bounding_box(width, lower, upper); + if(shape->test_AABB(lower, upper)) + { + potentially_overlapping_fids.push_back(fid); + break; + } + } + } + + const auto& candidate_faces = potentially_overlapping_fids; + const Integer num_candidates = candidate_faces.size(); + if(num_candidates == 0) + { + throw std::invalid_argument(""The shape does not overlap with polygon.""); + } + + const auto info = this->get_molecule_info(sp); + for(Integer i=0; irng_->uniform_int(0, num_candidates-1) + ); + const Real3 pos = this->polygon_->draw_position_on_face( + this->rng_, face_id + ); + + if(shape->is_inside(pos)) + { + const Particle p(sp, pos, info.radius, info.D); + std::tie(std::ignore, particle_inserted) = + this->new_particle(p, face_id); + } + // otherwise, particle_inserted is kept false. + } + } + return; +} + + +std::vector, Real> > +SGFRDWorld::list_particles_within_radius( + const std::pair& pos, const Real& radius) const +{ + std::vector, Real>> retval; + + // look particles on the same face + for(const auto& pid : this->list_particleIDs(pos.second)) + { + const std::pair pp = ps_->get_particle(pid); + const Real dist = length(pos.first - pp.second.position()) - + pp.second.radius(); + if(dist < radius) + { + retval.push_back(std::make_pair(pp, dist)); + } + } + + // look particles around + for(const auto& fid : polygon_->neighbor_faces_of(pos.second)) + { + for(const auto& pid : this->list_particleIDs(fid)) + { + const std::pair pp = ps_->get_particle(pid); + const Real dist = ecell4::polygon::distance(*polygon_, + pos, std::make_pair(pp.second.position(), get_face_id(pp.first)) + ) - pp.second.radius(); + if(dist < radius) + { + retval.push_back(std::make_pair(pp, dist)); + } + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + return retval; +} + +std::vector, Real> > +SGFRDWorld::list_particles_within_radius( + const std::pair& pos, const Real& radius, + const ParticleID& ignore) const +{ + std::vector, Real>> retval; + + // look particles on the same face + for(const auto& pid : this->list_particleIDs(pos.second)) + { + if(pid == ignore) + { + continue; + } + const std::pair pp = ps_->get_particle(pid); + const Real dist = length(pos.first - pp.second.position()) - + pp.second.radius(); + + if(dist < radius) + { + retval.push_back(std::make_pair(pp, dist)); + } + } + + for(const auto& fid : polygon_->neighbor_faces_of(pos.second)) + { + for(const auto& pid : this->list_particleIDs(fid)) + { + if(pid == ignore) + { + continue; + } + const std::pair pp = ps_->get_particle(pid); + const Real dist = ecell4::polygon::distance(*polygon_, + pos, std::make_pair(pp.second.position(), get_face_id(pp.first)) + ) - pp.second.radius(); + if(dist < radius) + { + retval.push_back(std::make_pair(pp, dist)); + } + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + return retval; +} + +std::vector, Real> > +SGFRDWorld::list_particles_within_radius( + const std::pair& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const +{ + std::vector, Real> > retval; + + {// same face + for(const auto& pid : this->list_particleIDs(pos.second)) + { + if(pid == ignore1 || pid == ignore2) + { + continue; + } + const std::pair pp = ps_->get_particle(pid); + const Real dist = length(pos.first - pp.second.position()) - + pp.second.radius(); + if(dist < radius) + { + retval.push_back(std::make_pair(pp, dist)); + } + } + } + + for(const auto& fid : polygon_->neighbor_faces_of(pos.second)) + { + for(const auto& pid : this->list_particleIDs(fid)) + { + if(pid == ignore1 || pid == ignore2) + { + continue; + } + const std::pair pp = ps_->get_particle(pid); + const Real dist = ecell4::polygon::distance(*polygon_, + pos, std::make_pair(pp.second.position(), get_face_id(pp.first)) + ) - pp.second.radius(); + if(dist < radius) + { + retval.push_back(std::make_pair(pp, dist)); + } + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + return retval; +} + + +bool SGFRDWorld::check_no_overlap( + const std::pair& pos, const Real& radius) const +{ + {// same face + const std::vector& ids = this->list_particleIDs(pos.second); + for(std::vector::const_iterator + i(ids.begin()), e(ids.end()); i != e; ++i) + { + const std::pair pp = ps_->get_particle(*i); + const Real dist = length(pos.first - pp.second.position()) - + pp.second.radius(); + if(dist < radius) {return false;} + } + } + + std::vector const& neighbors = + polygon_->neighbor_faces_of(pos.second); + for(std::vector::const_iterator + iter = neighbors.begin(); iter != neighbors.end(); ++iter) + { + const std::vector& ids = registrator_.elements_over(*iter); + for(std::vector::const_iterator + i(ids.begin()), e(ids.end()); i != e; ++i) + { + const std::pair pp = ps_->get_particle(*i); + const Real dist = ecell4::polygon::distance(*polygon_, pos, + std::make_pair(pp.second.position(), get_face_id(pp.first))) - + pp.second.radius(); + if(dist < radius) {return false;} + } + } + return true; +} + +bool SGFRDWorld::check_no_overlap( + const std::pair& pos, const Real& radius, + const ParticleID& ignore) const +{ + {// same face + const std::vector& ids = this->list_particleIDs(pos.second); + for(std::vector::const_iterator + i(ids.begin()), e(ids.end()); i != e; ++i) + { + if(*i == ignore) {continue;} + const std::pair pp = ps_->get_particle(*i); + const Real dist = length(pos.first - pp.second.position()) - + pp.second.radius(); + if(dist < radius) {return false;} + } + } + + std::vector const& neighbors = + polygon_->neighbor_faces_of(pos.second); + for(std::vector::const_iterator + iter = neighbors.begin(); iter != neighbors.end(); ++iter) + { + const std::vector& ids = this->list_particleIDs(*iter); + for(std::vector::const_iterator + i(ids.begin()), e(ids.end()); i != e; ++i) + { + if(*i == ignore) {continue;} + const std::pair pp = ps_->get_particle(*i); + const Real dist = ecell4::polygon::distance(*polygon_, pos, + std::make_pair(pp.second.position(), get_face_id(pp.first))) - + pp.second.radius(); + if(dist < radius) {return false;} + } + } + return true; +} + +bool SGFRDWorld::check_no_overlap( + const std::pair& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const +{ + {// same face + const std::vector& ids = this->list_particleIDs(pos.second); + for(std::vector::const_iterator + i(ids.begin()), e(ids.end()); i != e; ++i) + { + if(*i == ignore1 || *i == ignore2) {continue;} + const std::pair pp = ps_->get_particle(*i); + const Real dist = length(pos.first - pp.second.position()) - + pp.second.radius(); + if(dist < radius) {return false;} + } + } + + std::vector const& neighbors = + polygon_->neighbor_faces_of(pos.second); + for(std::vector::const_iterator + iter = neighbors.begin(); iter != neighbors.end(); ++iter) + { + const std::vector& ids = this->list_particleIDs(*iter); + for(std::vector::const_iterator + i(ids.begin()), e(ids.end()); i != e; ++i) + { + if(*i == ignore1 || *i == ignore2) {continue;} + const std::pair pp = ps_->get_particle(*i); + const Real dist = ecell4::polygon::distance(*polygon_, pos, + std::make_pair(pp.second.position(), get_face_id(pp.first))) - + pp.second.radius(); + if(dist < radius) {return false;} + } + } + return true; +} + +}// sgfrd +}// ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/Birth.hpp",".hpp","971","43","#ifndef ECELL4_SGFRD_BIRTH_DOMAIN +#define ECELL4_SGFRD_BIRTH_DOMAIN +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class Birth +{ + public: + + typedef ReactionRule reaction_rule_type; + + public: + + Birth(const Real dt, const Real begin_time, const ReactionRule& rule) + : dt_(dt), begin_time_(begin_time), rule_(rule) + {} + ~Birth(){} + + Real& dt() noexcept {return dt_;} + Real dt() const noexcept {return dt_;} + Real& begin_time() noexcept {return begin_time_;} + Real begin_time() const noexcept {return begin_time_;} + + ReactionRule& rule() noexcept {return rule_;} + ReactionRule const& rule() const noexcept {return rule_;} + + std::size_t num_shells() const noexcept {return 1;} + std::size_t multiplicity() const noexcept {return 1;} + + private: + + Real dt_; + Real begin_time_; + ReactionRule rule_; +}; +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_SINGLE_DOMAIN */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/MultiContainer.hpp",".hpp","8595","257","#ifndef ECELL4_SGFRD_MULTI_CONTAINER +#define ECELL4_SGFRD_MULTI_CONTAINER +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class MultiContainer +{ + public: + typedef SGFRDWorld world_type; + typedef Polygon polygon_type; + typedef world_type::structure_registrator_type structure_registrator_type; + typedef world_type::particle_space_type particle_space_type; + typedef world_type::particle_container_type particle_container_type; + typedef world_type::molecule_info_type molecule_info_type; + + public: + + MultiContainer(world_type& w) : world_(w){} + ~MultiContainer(){} + + bool make_entry(const ParticleID& pid) + { + if(this->find_(pid) != pcon_.end()) return false; + + pcon_.push_back(world_.get_particle(pid)); + if(world_.is_on_face(pid)) + { + registrator_.emplace(pid, world_.get_face_id(pid)); + } + return true; + } + + particle_container_type& list_particles() {return pcon_;} + particle_container_type const& list_particles() const {return pcon_;} + + std::size_t num_particles() const {return pcon_.size();} + + Real t() const {return world_.t();} + + FaceID get_face_id(const ParticleID& pid) const + {return world_.get_face_id(pid);} + + bool update_particle(const ParticleID& pid, const Particle& p, + const FaceID fid) + { + if(registrator_.have(pid)) + { + registrator_.update(pid, fid); + } + else + { + registrator_.emplace(pid, fid); + } + *(this->find_(pid)) = std::make_pair(pid, p); + + return world_.update_particle(pid, p, fid); + } + + std::pair, bool> + new_particle(const Particle& p, const FaceID& fid) + { + const std::pair, bool> result = + world_.new_particle(p, fid); + if(result.second) + { + this->pcon_.push_back(result.first); + registrator_.emplace(result.first.first, fid); + } + return result; + } + + void remove_particle(const ParticleID& pid) + { + if(registrator_.have(pid)) + { + registrator_.remove(pid); + } + const particle_container_type::iterator to_be_removed = this->find_(pid); + this->pcon_.erase(to_be_removed); + + return world_.remove_particle(pid); + } + void remove_particle(const ParticleID& pid, const FaceID& fid) + { + registrator_.remove(pid, fid); + const particle_container_type::iterator to_be_removed = this->find_(pid); + this->pcon_.erase(to_be_removed); + return world_.remove_particle(pid); + } + + // check particles associated with this Multi domain only. + std::vector, Real> > + list_particles_within_radius( + const std::pair& pos, const Real& radius) const + { + std::vector, Real> > retval; + Particle p; ParticleID pid; + for(const auto& pidp : this->pcon_) + { + std::tie(pid, p) = pidp; + auto fid = registrator_.structure_on(pid); + const Real d = world_.distance(std::make_pair(p.position(), fid), pos); + if(d <= (radius + p.radius())) + { + retval.push_back(std::make_pair(std::make_pair(pid, p), d)); + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + return retval; + } + std::vector, Real> > + list_particles_within_radius( + const std::pair& pos, const Real& radius, + const ParticleID& ignore) const + { + std::vector, Real> > retval; + Particle p; ParticleID pid; + for(const auto& pidp : this->pcon_) + { + std::tie(pid, p) = pidp; + if(pid == ignore){continue;} + auto fid = registrator_.structure_on(pid); + const Real d = world_.distance(std::make_pair(p.position(), fid), pos); + if(d <= (radius + p.radius())) + { + retval.push_back(std::make_pair(std::make_pair(pid, p), d)); + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + return retval; + } + std::vector, Real> > + list_particles_within_radius( + const std::pair& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const + { + std::vector, Real> > retval; + Particle p; ParticleID pid; + for(const auto& pidp : this->pcon_) + { + std::tie(pid, p) = pidp; + if(pid == ignore1 || pid == ignore2){continue;} + auto fid = registrator_.structure_on(pid); + const Real d = world_.distance(std::make_pair(p.position(), fid), pos); + if(d <= (radius + p.radius())) + { + retval.push_back(std::make_pair(std::make_pair(pid, p), d)); + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator< + std::pair, Real>()); + return retval; + } + + // return false if overlap exists. + bool check_no_overlap(const std::pair& pos, + const Real& radius) const + { + std::vector, Real> > retval; + Particle p; ParticleID pid; + for(const auto& pidp : this->pcon_) + { + std::tie(pid, p) = pidp; + auto fid = registrator_.structure_on(pid); + const Real dist = + this->world_.distance(std::make_pair(p.position(), fid), pos); + if(dist <= radius + p.radius()) + { + return false; // overlaps! + } + } + return true; // no overlap! + } + bool check_no_overlap(const std::pair& pos, + const Real& radius, const ParticleID& ignore) const + { + std::vector, Real> > retval; + Particle p; ParticleID pid; + for(const auto& pidp : this->pcon_) + { + std::tie(pid, p) = pidp; + if(pid == ignore){continue;} + + auto fid = registrator_.structure_on(pid); + const Real dist = + this->world_.distance(std::make_pair(p.position(), fid), pos); + if(dist <= radius + p.radius()) + { + return false; // overlaps! + } + } + return true; // no overlap! + } + bool check_no_overlap(const std::pair& pos, + const Real& radius, const ParticleID& ignore1, + const ParticleID& ignore2) const + { + std::vector, Real> > retval; + Particle p; ParticleID pid; + for(const auto& pidp : this->pcon_) + { + std::tie(pid, p) = pidp; + if(pid == ignore1 || pid == ignore2){continue;} + + auto fid = registrator_.structure_on(pid); + const Real dist = + this->world_.distance(std::make_pair(p.position(), fid), pos); + if(dist <= radius + p.radius()) + { + return false; // overlaps! + } + } + return true; // no overlap! + } + + world_type const& world() const throw() {return world_;} + + std::pair get_particle(const ParticleID& pid) const + { + return this->world_.get_particle(pid); + } + + MoleculeInfo get_molecule_info(const Species& sp) const + { + return world_.get_molecule_info(sp); + } + + private: + + particle_container_type::iterator find_(const ParticleID& pid) + { + return std::find_if(pcon_.begin(), pcon_.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(pid)); + } + + private: + + world_type& world_; + structure_registrator_type registrator_; + particle_container_type pcon_; +}; + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_MULTI_CONTAINER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/ShellVisitors.hpp",".hpp","2128","92","#ifndef ECELL4_SGFRD_SHELL_VISITORS +#define ECELL4_SGFRD_SHELL_VISITORS +#include ""Shell.hpp"" +#include ""SGFRDEvent.hpp"" +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +struct minimal_eval_or : std::true_type +{ + static bool is_resolved(const bool v) {return v;} +}; + +struct minimal_eval_and : std::false_type +{ + static bool is_resolved(const bool v) {return !v;} +}; + +struct domain_id_setter : boost::static_visitor +{ + DomainID did_; + domain_id_setter(DomainID did) : did_(did){} + + template + void operator()(Shell& shell) const + { + shell.domain_id() = did_; + } +}; + +struct domain_id_getter : boost::static_visitor +{ + template + DomainID operator()(const Shell& shell) const + { + return shell.domain_id(); + } +}; + +struct shell_size_getter : boost::static_visitor +{ + template + Real operator()(const Shell& shell) const + { + return shell.size(); + } +}; + +struct shell_position_getter : boost::static_visitor +{ + template + Real3 operator()(const Shell& shell) const + { + return shell.position(); + } +}; + +struct inside_checker : boost::static_visitor +{ + typedef minimal_eval_or eval_manner; + typedef ecell4::Polygon polygon_type; + + + inside_checker(Real3 pos, Real rad, FaceID f, polygon_type const& p) + : radius(rad), position(pos), fid(f), poly(p) + {} + + //XXX: dispatch using shapeT::dimension to use 3D shells + template + bool operator()(const Shell& shell) const + { + return ecell4::polygon::distance(poly, + std::make_pair(shell.position(), shell.structure_id()), + std::make_pair(position, fid)) < shell.size() - radius; + } + + private: + + Real radius; + Real3 position; + FaceID fid; + polygon_type const& poly; +}; + + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_SHELL_VISITORS +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/SGFRDFactory.hpp",".hpp","4582","153","#ifndef ECELL4_SGFRD_SGFRD_FACTORY_HPP +#define ECELL4_SGFRD_SGFRD_FACTORY_HPP +#include +#include +#include +#include ""SGFRDWorld.hpp"" +#include ""SGFRDSimulator.hpp"" + +namespace ecell4 +{ +namespace sgfrd +{ + +class SGFRDFactory : + public SimulatorFactory +{ + public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef SGFRDFactory this_type; + + public: + + SGFRDFactory(const Integer3& matrix_sizes = default_matrix_sizes(), + Real bd_dt_factor = default_bd_dt_factor(), + Real bd_reaction_length_factor = default_bd_reaction_length_factor()) + : base_type(), rng_(nullptr), polygon_(nullptr), + polygon_file_("""", STLFormat::Ascii), + matrix_sizes_(matrix_sizes), bd_dt_factor_(bd_dt_factor), + bd_reaction_length_factor_(bd_reaction_length_factor) + { + ; // do nothing + } + virtual ~SGFRDFactory() override = default; + + static inline Integer3 default_matrix_sizes() + { + return Integer3(3, 3, 3); + } + + static inline Real default_bd_dt_factor() + { + return 0.01; // relative to the upper limit; for safety + } + + static inline Real default_bd_reaction_length_factor() + { + return 0.1; // 0.05 ~ 0.1 + } + + this_type& rng(const std::shared_ptr& rng) + { + rng_ = rng; + return (*this); + } + + inline this_type* rng_ptr(const std::shared_ptr& rng) + { + return std::addressof(this->rng(rng)); + } + + // ----------------------------------------------------------------------- + // get polygon from a list of triangles + + this_type& polygon(const Real3& el, const std::vector& ts) + { + polygon_file_.first = """"; // XXX clear polygon file + + this->polygon_ = std::make_shared(el, ts); + return (*this); + } + this_type* polygon_ptr(const Real3& el, const std::vector& ts) + { + return std::addressof(this->polygon(el, ts)); + } + + // ----------------------------------------------------------------------- + // read polygon from .STL file + + this_type& polygon(const std::string& fname, const STLFormat fmt) + { + polygon_ = nullptr; // XXX clear polygon structure + + this->polygon_file_ = std::make_pair(fname, fmt); + return (*this); + } + this_type* polygon_ptr(const std::string& fname, const STLFormat fmt) + { + return std::addressof(this->polygon(fname, fmt)); + } + + protected: + + virtual world_type* create_world(const Real3& edge_lengths) const override + { + if (rng_) + { + if(this->polygon_) + { + return new world_type(edge_lengths, matrix_sizes_, rng_, + this->polygon_); + } + else if(!this->polygon_file_.first.empty()) + { + return new world_type(edge_lengths, matrix_sizes_, rng_, + this->polygon_file_.first, this->polygon_file_.second); + } + else + { + return new world_type(edge_lengths, matrix_sizes_, rng_); + } + } + else + { + if(this->polygon_) + { + return new world_type(edge_lengths, matrix_sizes_, + this->polygon_); + } + else if(!this->polygon_file_.first.empty()) + { + return new world_type(edge_lengths, matrix_sizes_, + this->polygon_file_.first, this->polygon_file_.second); + } + else + { + return new world_type(edge_lengths, matrix_sizes_); + } + } + } + + virtual simulator_type* create_simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const override + { + return new simulator_type(w, m, bd_dt_factor_, bd_reaction_length_factor_); + } + + protected: + + std::shared_ptr rng_; + std::shared_ptr polygon_; + std::pair polygon_file_; + Integer3 matrix_sizes_; + Real bd_dt_factor_; + Real bd_reaction_length_factor_; +}; + +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_SGFRD_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/statistics.hpp",".hpp","1869","105","#ifndef ECELL4_SGFRD_STATISTICS +#define ECELL4_SGFRD_STATISTICS +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +template +class statistics +{ + public: + typedef std::size_t count_type; + typedef std::map container_type; + + public: + + void add_count(const Kind& k) + { + if(this->values_.count(k) == 0) + { + this->values_[k] = 0; + } + this->values_[k] += 1; + return; + } + + std::size_t total() const + { + std::size_t tot = 0; + for(typename container_type::const_iterator + i(values_.begin()), e(values_.end()); i != e; ++i) + { + tot += i->second; + } + return tot; + } + + std::size_t show_count(const Kind& k) const + { + if(this->values_.count(k) == 0) + { + return 0; + } + return values_.find(k)->second; + } + + double show_percent(const Kind& k) const + { + return (100.0 * this->show_count(k)) / this->total(); + } + + std::vector list_all_kinds() const + { + std::vector ks; + for(typename container_type::const_iterator + i(values_.begin()), e(values_.end()); i != e; ++i) + { + ks.push_back(i->first); + } + return ks; + } + + private: + container_type values_; +}; + +enum ReactionKind +{ + SingleFirstOrder, + SingleFirstOrderFailed, + PairFirstOrder, + PairFirstOrderFailed, + PairSecondOrder, + PairSecondOrderFailed, + MultiFirstOrder, + MultiSecondOrder +}; + +enum EventFired +{ + FireSingleCircular, + FireSingleConical, + FirePair, + FireMulti, + FireBirth +}; + +enum MultiReason +{ + SingleConicalFailed, + PairFailed +}; + +#ifndef STATISTICS_OFF +#define STAT(x) x +#else +#define STAT(x) /**/ +#endif + +} // sgfrd +} // ecell4 +#endif // ECELL4_SGFRD_STATISTICS +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/SGFRDSimulator.cpp",".cpp","72881","1772","#include ""SGFRDSimulator.hpp"" +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +// Note that if `single_circular_shell_factor` is smaller than +// `1 + reaciton_length_factor` in BD, it causes a strange results. +// Please make sure that the value is sufficiently large. +const Real SGFRDSimulator::single_circular_shell_factor = 1.2; +const Real SGFRDSimulator::single_circular_shell_mergin = 1.0 - 1e-7; +const Real SGFRDSimulator::single_conical_surface_shell_factor = 1.2; +const Real SGFRDSimulator::single_conical_surface_shell_mergin = 1.0 - 1e-7; +const Real SGFRDSimulator::minimum_separation_factor = 1e-7; + +std::tuple +SGFRDSimulator::propagate_single_circular( + const circular_shell_type& sh, const Single& dom, const Real tm) +{ + SGFRD_SCOPE(us, propagate_single_circular, tracer_); + + Particle p = dom.particle(); + ParticleID pid = dom.particle_id(); + const FaceID fid = this->get_face_id(pid); + + if(p.D() == 0.0) + { + // it never moves. + return std::make_tuple(pid, p, fid); + } + + greens_functions::GreensFunction2DAbsSym gf(p.D(), sh.size() - p.radius()); + + const Real del_t = tm - dom.begin_time(); + + SGFRD_TRACE(tracer_.write(""delta t for domain having shell %1% is %2%"", + del_t, dom.shell_id())); + SGFRD_TRACE(tracer_.write(""its own dt = %1%, and begin_time = %2%"", + dom.dt(), dom.begin_time())); + + const Real r = gf.drawR(this->uniform_real(), del_t); + const Real theta = this->uniform_real() * 2 * M_PI; + + SGFRD_TRACE(tracer_.write(""r = %1%, theta = %2%"", r, theta)); + + const Triangle& face = this->polygon().triangle_at(fid); + const Real3 direction = rotate(theta, face.normal(), face.represent()); + const Real len_direction = length(direction); + + SGFRD_TRACE(tracer_.write(""direction = %1%, len = %2%"", direction, len_direction)); + + std::pair, Real3> state = + std::make_pair(std::make_pair(p.position(), fid), + direction * r / len_direction); + + SGFRD_TRACE(tracer_.write(""pos = %1%, fid = %2%"", state.first.first, state.first.second)); + + state.first = ecell4::polygon::travel(this->polygon(), state.first, state.second, 2); + + SGFRD_TRACE(tracer_.write(""pos = %1%, fid = %2%, dsp = %3%"", + state.first.first, state.first.second, state.second)) + + p.position() = state.first.first; + this->update_particle(pid, p, state.first.second); + SGFRD_TRACE(tracer_.write(""particle updated"")) + + assert(// check particle is still inside of the shell after this propagation + p.radius() + ecell4::polygon::distance(this->polygon(), + state.first, std::make_pair(sh.position(), sh.structure_id())) + <= sh.size() * (1.0 + minimum_separation_factor) + ); + + return std::make_tuple(pid, p, state.first.second); +} + +std::tuple +SGFRDSimulator::propagate_single_conical( + const conical_surface_shell_type& sh, const Single& dom, const Real tm) +{ + SGFRD_SCOPE(us, propagate_single_conical, tracer_); + + Particle p = dom.particle(); + const ParticleID pid = dom.particle_id(); + const FaceID fid = this->get_face_id(pid); + + if(p.D() == 0.0) + { + // it never moves. + return std::make_tuple(pid, p, fid); + } + + SGFRD_TRACE(tracer_.write(""pos = %1%, fid = %2%"", p.position(), fid)); + + const Real D = p.D(); + const Real a = sh.size() - p.radius(); + const Real phi = sh.shape().apex_angle(); + const Real r0 = length( + this->polygon().periodic_transpose(p.position(), sh.shape().apex()) - + sh.shape().apex()); + + greens_functions::GreensFunction2DRefWedgeAbs gf(D, r0, a, phi); + + const Real del_t = tm - dom.begin_time(); + const Real r = gf.drawR(this->uniform_real(), del_t); + const Real theta = gf.drawTheta(this->uniform_real(), r, del_t); + // RefWedgeAbs::drawTheta returns [-phi, phi]. + + SGFRD_TRACE(tracer_.write(""r = %1%, theta = %2%"", r, theta)); + + const std::pair state = + ecell4::polygon::roll(this->polygon(), std::make_pair(p.position(), fid), + sh.structure_id(), r, theta); + SGFRD_TRACE(tracer_.write(""propagateed : pos = %1%, fid = %2%"", + state.first, state.second)); + + p.position() = state.first; + this->update_particle(pid, p, state.second); + SGFRD_TRACE(tracer_.write(""particle updated"")) + + assert(// check particle is still inside of the shell after this propagation + length(polygon().periodic_transpose(p.position(), sh.shape().apex()) - + sh.shape().apex()) + p.radius() + <= sh.size() * (1.0 + minimum_separation_factor) + ); + + return std::make_tuple(pid, p, state.second); +} + +boost::container::static_vector< + std::tuple, 2> +SGFRDSimulator::reaction_single( + const shell_type& sh, const Single& dom, const DomainID did) +{ + // considering shell remains + SGFRD_SCOPE(us, reaction_single, tracer_) + ParticleID pid; Particle p; FaceID fid; + std::tie(pid, p, fid) = this->propagate_single(sh, dom, this->time()); + return attempt_reaction_single(sh, did, dom, pid, p, fid); +} + +boost::container::static_vector +SGFRDSimulator::attempt_reaction_single( + const shell_type& sh, const DomainID did, const Single& dom, + const ParticleID& pid, const Particle& p, const FaceID& fid) +{ + SGFRD_SCOPE(us, attempt_reaction_single, tracer_) + + const auto rules = this->model_->query_reaction_rules(p.species()); + if(rules.empty()) + { + SGFRD_TRACE(tracer_.write(""rule is empty. return particle kept intact"")) + return boost::container::static_vector(1, + std::make_tuple(pid, p, fid)); + } + const ReactionRule& rule = determine_reaction_rule(rules); + + switch(rule.products().size()) + { + case 0: + { + SGFRD_TRACE(tracer_.write(""degradation reaction occurs."")) + this->remove_particle(pid, fid); + last_reactions_.push_back(std::make_pair(rule, + make_degradation_reaction_info(this->time(), pid, p))); + return boost::container::static_vector(0); + } + case 1: + { + SGFRD_TRACE(tracer_.write(""attempting 1 to 1 reaction."")) + return attempt_reaction_1_to_1(rule, sh, did, dom, pid, p, fid); + } + case 2: + { + SGFRD_TRACE(tracer_.write(""attempting 1 to 2 reaction."")) + return attempt_reaction_1_to_2(rule, sh, did, dom, pid, p, fid); + } + default: throw NotImplemented(""SGFRD Single Reaction:"" + ""more than two products from one reactant are not allowed""); + } +} + +boost::container::static_vector +SGFRDSimulator::attempt_reaction_1_to_1(const ReactionRule& rule, + const shell_type& sh, const DomainID did, const Single& dom, + const ParticleID& pid, const Particle& p, const FaceID& fid) +{ + SGFRD_SCOPE(us, attempt_reaction_1_to_1, tracer_) + + const auto species_new = rule.products().front(); + const auto molinfo = this->world_->get_molecule_info(species_new); + const Real radius_new = molinfo.radius; + const Real D_new = molinfo.D; + + const Particle p_new(species_new, p.position(), radius_new, D_new); + + inside_checker is_inside_of( + p_new.position(), p_new.radius(), fid, this->polygon()); + if(!boost::apply_visitor(is_inside_of, sh)) + { + SGFRD_SCOPE(us, particle_goes_outside, tracer_) + // particle goes outside of the shell. must clear the volume. + const bool no_overlap = this->burst_and_shrink_overlaps(p_new, fid, did); + SGFRD_TRACE(tracer_.write(""no_overlap = %1%"", no_overlap)) + if(!no_overlap) + {// cannot avoid overlapping... reject the reaction. + SGFRD_TRACE(tracer_.write(""reject the reaction because of no space"")) + return boost::container::static_vector( + 1, std::make_tuple(pid, p, fid)); + } + } + + SGFRD_TRACE(tracer_.write(""reaction is accepted."")) + // reaction occurs. record this reaction to `last_reactions`. + last_reactions_.push_back(std::make_pair(rule, + make_unimolecular_reaction_info(this->time(), pid, p, pid, p_new))); + + // update particle and return resulting particles. + this->update_particle(pid, p_new, fid); + SGFRD_TRACE(tracer_.write(""particle updated."")) + return boost::container::static_vector( + 1, std::make_tuple(pid, p_new, fid)); +} + +boost::container::static_vector +SGFRDSimulator::attempt_reaction_1_to_2(const ReactionRule& rule, + const shell_type& sh, const DomainID did, const Single& dom, + const ParticleID& pid, const Particle& p, const FaceID& fid) +{ + SGFRD_SCOPE(us, attempt_reaction_1_to_2, tracer_) + + const auto sp1 = rule.products().at(0); + const auto sp2 = rule.products().at(1); + + const auto molinfo1 = this->world_->get_molecule_info(sp1); + const auto molinfo2 = this->world_->get_molecule_info(sp2); + + const Real D1 = molinfo1.D; + const Real D2 = molinfo2.D; +// const Real D12 = D1 + D2 + const Real r1 = molinfo1.radius; + const Real r2 = molinfo2.radius; + const Real r12 = r1 + r2; + + SGFRD_TRACE(tracer_.write(""products has D1(%1%), D2(%2%), r1(%3%), r2(%4%)"", + D1, D2, r1, r2)); + + std::array, 2> newpfs; + newpfs[0] = std::make_pair(p.position(), fid); + newpfs[1] = std::make_pair(p.position(), fid); + + std::array particles_new; + particles_new[0] = Particle(sp1, newpfs[0].first, r1, D1); + particles_new[1] = Particle(sp2, newpfs[1].first, r2, D2); + + bool rejected = false; + Real separation_factor = r12 * minimum_separation_factor; + std::size_t separation_count = 10; + while(separation_count != 0) + { + --separation_count; + SGFRD_SCOPE(us, try_to_split, tracer_); + + SGFRD_TRACE(tracer_.write(""separation count = %1%"", separation_count)); + + const Real3 ipv(random_circular_uniform(r12 + separation_factor, fid)); + SGFRD_TRACE(tracer_.write(""length of ipv drawn now is %1%"", length(ipv))); + + Real3 disp1(ipv * ( r1 / r12)), disp2(ipv * (-r2 / r12)); + + newpfs[0] = ecell4::polygon::travel(this->polygon(), newpfs[0], disp1); + newpfs[1] = ecell4::polygon::travel(this->polygon(), newpfs[1], disp2); + + // if two particle overlaps... + const Real dist = + ecell4::polygon::distance(this->polygon(), newpfs[0], newpfs[1]); + if(dist <= r12) + { + newpfs[0] = std::make_pair(p.position(), fid); // rollback + newpfs[1] = std::make_pair(p.position(), fid); + separation_factor *= 2.0; + continue; + } + + // check whether new particles are inside of the shell, reject the move. + { + particles_new[0].position() = newpfs[0].first; + inside_checker + is_inside_of(newpfs[0].first, r1, newpfs[0].second, this->polygon()); + if(!boost::apply_visitor(is_inside_of, sh)) + { + const bool no_overlap = this->burst_and_shrink_overlaps( + particles_new[0], newpfs[0].second, did); + if(!no_overlap) + { + rejected = true; + break; + } + } + } + { + particles_new[1].position() = newpfs[1].first; + inside_checker + is_inside_of(newpfs[1].first, r2, newpfs[1].second, this->polygon()); + if(!boost::apply_visitor(is_inside_of, sh)) + { + const bool no_overlap = this->burst_and_shrink_overlaps( + particles_new[1], newpfs[1].second, did); + if(!no_overlap) + { + rejected = true; + break; + } + } + } + break; + } + if(rejected) + { + SGFRD_TRACE(tracer_.write(""reaction is rejected because there are no space."")) + return boost::container::static_vector( + 1, std::make_tuple(pid, p, fid)); + } + + SGFRD_TRACE(tracer_.write(""single reaction 1(%1%) -> 2 occurs"", pid)) + + //------------------------ update particles ----------------------------- + this->update_particle(pid, particles_new[0], newpfs[0].second); + std::pair, bool> + pp2 = this->create_particle(particles_new[1], newpfs[1].second); + assert(pp2.second); + const ParticleID pid2(pp2.first.first); + SGFRD_TRACE(tracer_.write(""ext particle %1% is updateed"", pid)) + SGFRD_TRACE(tracer_.write(""new particle %1% is assigned"", pid2)) + + //------------------------ record reaction ----------------------------- + last_reactions_.push_back(std::make_pair(rule, make_unbinding_reaction_info( + this->time(), pid, p, pid, particles_new[0], pid2, particles_new[1]))); + + boost::container::static_vector retval(2); + retval[0] = std::make_tuple(pid , particles_new[0], newpfs[0].second); + retval[1] = std::make_tuple(pid2, particles_new[1], newpfs[1].second); + return retval; +} + +std::tuple +SGFRDSimulator::escape_single_circular( + const circular_shell_type& sh, const Single& dom) +{ + SGFRD_SCOPE(us, escape_single_circular, tracer_); + + if(sh.size() == dom.particle().radius()) + { + SGFRD_TRACE(tracer_.write(""closely fitted shell. didnot move."")); + return std::make_tuple(dom.particle_id(), dom.particle(), + this->get_face_id(dom.particle_id())); + } + + Particle p = dom.particle(); + ParticleID pid = dom.particle_id(); + + const Real r = sh.size() - p.radius(); + const Real theta = this->uniform_real() * 2.0 * M_PI; + + SGFRD_TRACE(tracer_.write(""r = %1%, theta = %2%"", r, theta)) + + const FaceID fid = this->get_face_id(pid); + const Triangle& face = this->polygon().triangle_at(fid); + const Real3 direction = rotate(theta, face.normal(), face.represent()); + + SGFRD_TRACE(tracer_.write(""dir = %1%, len = %2%"", direction, length(direction))) + + const Real3 displacement = direction * r / length(direction); + SGFRD_TRACE(tracer_.write(""displacement = %1%"", displacement)) + + std::pair, Real3> state = + std::make_pair(std::make_pair(p.position(), fid), displacement); + + SGFRD_TRACE(tracer_.write(""pos = %1%, fid = %2%"", state.first.first, state.first.second)) + + state.first = ecell4::polygon::travel(this->polygon(), state.first, state.second, 2); + SGFRD_TRACE(tracer_.write(""escaped. pos = %1%, fid = %2%"", + state.first.first, state.first.second)) + + p.position() = state.first.first; + this->update_particle(pid, p, state.first.second); + SGFRD_TRACE(tracer_.write(""particle updated"")) + + assert(// check particle is still inside of the shell after this propagation + p.radius() + ecell4::polygon::distance(this->polygon(), + state.first, std::make_pair(sh.position(), sh.structure_id())) + <= sh.size() * (1.0+minimum_separation_factor)); + + return std::make_tuple(pid, p, state.first.second); +} + +std::tuple +SGFRDSimulator::escape_single_conical( + const conical_surface_shell_type& sh, const Single& dom) +{ + SGFRD_SCOPE(us, escape_single_conical, tracer_); + + Particle p = dom.particle(); + const ParticleID pid = dom.particle_id(); + const FaceID fid = this->get_face_id(pid); + + SGFRD_TRACE(tracer_.write(""pos = %1%, fid = %2%"", p.position(), fid)) + + const Real r = sh.size() - p.radius(); + greens_functions::GreensFunction2DRefWedgeAbs + gf(p.D(), length(p.position() - sh.position()), + r, sh.shape().apex_angle()); + const Real theta = gf.drawTheta(this->uniform_real(), r, dom.dt()); + // RefWedgeAbs::drawTheta returns [-phi, phi]. + + SGFRD_TRACE(tracer_.write(""r = %1%, theta = %2%"", r, theta)) + + const std::pair state = + ecell4::polygon::roll(this->polygon(), std::make_pair(p.position(), fid), + sh.structure_id(), r, theta); + SGFRD_TRACE(tracer_.write(""escaped. pos = %1%, fid = %2%"", + state.first, state.second)); + + p.position() = state.first; + this->update_particle(pid, p, state.second); + SGFRD_TRACE(tracer_.write(""particle updated"")) + + assert(// check particle is still inside of the shell after this propagation + length(polygon().periodic_transpose(p.position(), sh.shape().apex()) - + sh.shape().apex()) + p.radius() + <= sh.size() * (1.0 + minimum_separation_factor) + ); + + return std::make_tuple(pid, p, state.second); +} + +SGFRDSimulator::bursted_type +SGFRDSimulator::burst_single(const Single& dom, const Real tm) +{ + SGFRD_SCOPE(us, burst_single, tracer_); + const ShellID sid(dom.shell_id()); + SGFRD_TRACE(tracer_.write(""shell id = %1%"", sid)); + bursted_type results; + results.push_back(this->propagate_single(this->get_shell(sid), dom, tm)); + this->remove_shell(sid); + SGFRD_TRACE(tracer_.write(""shell removed"")); + return results; +} + +void SGFRDSimulator::fire_single(const Single& dom, DomainID did) +{ + STAT(if(this->get_shell(dom.shell_id()).which() == + shell_container_type::circular_shell){ + stat_fired_events.add_count(FireSingleCircular); + } else { + stat_fired_events.add_count(FireSingleConical); + }) + + SGFRD_SCOPE(us, fire_single, tracer_); + SGFRD_TRACE(tracer_.write(""fire single domain %1%"", did)) + + const ShellID sid(dom.shell_id()); + switch(dom.eventkind()) + { + case Single::ESCAPE: + { + SGFRD_SCOPE(us, single_escape, tracer_); + + ParticleID pid; Particle p; FaceID fid; + std::tie(pid, p, fid) = + this->escape_single(this->get_shell(sid), dom); + + this->remove_shell(sid); + SGFRD_TRACE(tracer_.write(""shell %1% removed"", sid)) + + SGFRD_TRACE(tracer_.write(""adding next event for %1%"", pid)) + this->create_event(pid, p, fid); + return; + } + case Single::REACTION: + { + SGFRD_SCOPE(us, single_reaction, tracer_); + const ParticleID old_pid = dom.particle_id(); + + auto results = this->reaction_single(this->get_shell(sid), dom, did); + this->remove_shell(sid); + + if(results.size() != 1 || std::get<0>(results.front()) != old_pid) + { + STAT(stat_reaction_condition.add_count(SingleFirstOrder)); + } + else + { + STAT(stat_reaction_condition.add_count(SingleFirstOrderFailed)); + } + + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : results) + { + std::tie(pid, p, fid) = pidpf; + SGFRD_TRACE(tracer_.write(""adding next event for %1%"", pid)) + // here, by calling create_event, the first domain might include + // the other particle that is one of the result of 1->2 reaction + add_event(create_tight_domain( + create_tight_shell(pid, p, fid), pid, p)); + } + return; + } + case Single::UNKNOWN: + { + throw std::logic_error(""when firing Single: event unspecified""); + } + default: + { + throw std::logic_error(""when firing Single: invalid enum value""); + } + }// switch +} + +bool SGFRDSimulator::burst_and_shrink_overlaps( + const Particle& p, const FaceID& fid, const DomainID& did) +{ + // Here, particle is being outside of a shell, by reaction or BDstep. + // But before bursting, the particle is not assigned to World. + // So it has no ID. + SGFRD_SCOPE(us, burst_and_shrink_overlaps, tracer_); + const Real tm = this->time(); + auto intruders = this->get_intrusive_domains( + std::make_pair(p.position(), fid), p.radius()); + + SGFRD_TRACE(tracer_.write(""there are %1% intruders"", intruders.size())) + + bool no_overlap = true; + DomainID did_; + for(const auto& didd : intruders) + { + SGFRD_SCOPE(ms, intruders, tracer_) + std::tie(did_, std::ignore) = didd; + SGFRD_TRACE(tracer_.write(""burst domain %1%"", did_)) + + if(did == did_) + { + SGFRD_TRACE(tracer_.write(""domain %1% was ignored"", did_)) + continue; + } + if(!(this->event_exists(did_))) + { + SGFRD_TRACE(tracer_.write(""domain %1% does not exist. it may have "" + ""already been fired."", did_)); + throw std::runtime_error(""domain does not exist""); + } + + std::shared_ptr ev_(get_event(did_)); + + if(ev_->which_domain() == SGFRDEvent::multi_domain) + { + // Multi overlaps with Multi. it sometimes causes recursive bursting. + // in this case, it is considered as a collision. + no_overlap = false; + continue; + } + + ParticleID pid_; Particle p_; FaceID fid_; + for(const auto& pidpf : burst_event(std::make_pair(did_, ev_), tm)) + { + std::tie(pid_, p_, fid_) = pidpf; + const Real dist = ecell4::polygon::distance(this->polygon(), + std::make_pair(p.position(), fid), + std::make_pair(p_.position(), fid_)); + no_overlap = no_overlap && (dist > p.radius() + p_.radius()); + add_event(create_tight_domain( + create_tight_shell(pid_, p_, fid_), pid_, p_)); + } + remove_event(did_); + } + return no_overlap; +} + +boost::optional +SGFRDSimulator::form_pair( + const ParticleID& pid, const Particle& p, const FaceID& fid, + const std::vector >& intruders) +{ + SGFRD_SCOPE(us, form_pair, tracer_); + + // the first (nearest) domain in the intruders is the partner to form pair. + const std::shared_ptr nearest = + this->get_event(intruders.front().first); + if(nearest->which_domain() != event_type::single_domain) + { + // if the partner is Pair of Multi, pair cannot be formed. + SGFRD_TRACE(tracer_.write( + ""nearest intruder is not single. can't form pair."")) + return boost::none; + } + + // the domain that will be consumed to form a pair. + const Single& sgl = boost::get(nearest->domain()); + const ParticleID partner_id = sgl.particle_id(); + const Particle partner = sgl.particle(); + + if(p.D() == 0.0 && partner.D() == 0.0) + { + return boost::none; + } + + if(sgl.dt() != 0.0) + { + SGFRD_TRACE(tracer_.write(""Nearest intruder is not a tight single. "" + ""We need to burst it before forming Pair"")); + return boost::none; + } + + const FaceID partner_fid = this->get_face_id(partner_id); + const ShellID partner_sid = sgl.shell_id(); + const DomainID partner_did = intruders.front().first; + + SGFRD_TRACE(tracer_.write( + ""try to form pair domain for %1% and %2%"", pid, partner_id)) + + const Real r1(p.radius()), r2(partner.radius()); + const Real D1(p.D()), D2(partner.D()); + const Real D12 = D1 + D2; + const Real r12 = r1 + r2; + + const Real3 ipv = ecell4::polygon::direction(this->polygon(), + std::make_pair(p.position(), fid), // -> + std::make_pair(partner.position(), partner_fid)); + const Real len_ipv = length(ipv); + const Real sh_minim = + std::max(len_ipv * D1 / D12 + r1, len_ipv * D2 / D12 + r2) * 3; + // XXX this `3` is just a parameter. it should be tuned later. + + if(len_ipv < r12) + { + throw std::runtime_error((boost::format( + ""form_pair: particle %1% and %2% already collides!\n"" + ""len_ipv = %3%\n"" + ""r1 = %4%\n"" + ""r2 = %5%\n"" + ""r12 = %6%\n"") % pid % partner_id % len_ipv % r1 % r2 % r12 + ).str()); + } + + const std::pair pos_com = ecell4::polygon::travel( + this->polygon(), std::make_pair(p.position(), fid), ipv * D1 / D12, 2); + + // check other shells are not in the range... + Real max_dist = get_max_circle_size(pos_com); + for(auto iter(intruders.begin()+1), iend(intruders.end()); iter != iend; ++iter) + { + const std::shared_ptr intruder_ev(this->get_event(iter->first)); + if(intruder_ev->which_domain() != event_type::single_domain) + { + continue; + } + const Single& intruder_dom = boost::get(nearest->domain()); + const ParticleID intruder_pid = intruder_dom.particle_id(); + const Particle& intruder_p = intruder_dom.particle(); + const FaceID intruder_fid = this->get_face_id(intruder_pid); + + const Real d_to_sh = ecell4::polygon::distance(this->polygon(), + pos_com, std::make_pair(intruder_p.position(), intruder_fid)) - + calc_min_single_circular_shell_radius(intruder_p); + + if(d_to_sh < sh_minim) + { + SGFRD_TRACE(tracer_.write( + ""intrusive domains exists. multi should be formed"")) + // other shells overlap to the pair. multi should be formed. + return boost::none; + } + max_dist = std::min(max_dist, d_to_sh); + } + + Real pair_shell_size = max_dist; + for(auto&& shid_sh_dist : + shell_container_.list_shells_within_radius(pos_com, max_dist)) + { + if(shid_sh_dist.first.first == partner_sid) + { + continue; + } + pair_shell_size = std::min(pair_shell_size, shid_sh_dist.second); + } + + const Real effective_pair_shell_size = + (pair_shell_size * single_circular_shell_mergin - + std::max(p.radius(), partner.radius())); + + // maximum available pair shell size determined! + if(effective_pair_shell_size >= sh_minim && // pair shell size should be large enough + Pair::calc_R_ipv(effective_pair_shell_size, p, partner) > len_ipv)// ipv must be inside + { + SGFRD_TRACE(tracer_.write(""pair shell size is larger than the minimum. "" + ""pair can be formed"")) + + this->remove_shell(partner_sid); + SGFRD_TRACE(tracer_.write(""remove partner's shell, %1%"", partner_sid)) + + this->remove_event(partner_did); + SGFRD_TRACE(tracer_.write(""remove partner's domain, %1%"", partner_did)) + + // check that the pair shell does not overlap with other particles + assert(get_intrusive_domains(pos_com, pair_shell_size).empty()); + + const ShellID shid(shell_id_gen()); + const circle_type pair_circle( + pair_shell_size * single_circular_shell_mergin, pos_com.first, + this->polygon().triangle_at(pos_com.second).normal()); + const circular_shell_type pair_shell(pair_circle, pos_com.second); + shell_container_.check_add_shell(shid, pair_shell, pos_com.second, + ""create pair shell""); + + SGFRD_TRACE(tracer_.write(""pair shell size = %1%"", pair_shell_size);) + + if(pos_com.second == fid) + { + // ipv is determined on the face `fid` where the particle belongs to. + // if the CoM locates on the same triangle, it's okay to store it + // as an ipv of the shell because the displacement will be calculated + // based on the position of CoM. + return add_event(create_pair( + std::make_pair(shid, pair_circle), + pid, p, partner_id, partner, ipv, len_ipv)); + } + else + { + // if the CoM of p and partner locates on a different triangle, + // we need to re-calculate ipv. since different triangle can have + // different normal vector, so when the ipv is applied to particles, + // the position can be invalid. + + const auto ipv_opposite = ecell4::polygon::direction(this->polygon(), + std::make_pair(partner.position(), partner_fid), + std::make_pair(p.position(), fid)); + + if(std::abs(length(ipv_opposite) - length(ipv)) > 1e-6) + { + throw std::runtime_error(""inter-particle vector changes in each"" + "" direction. Polygon has an abnormal shape or"" + "" some internal error happens.""); + } + + return add_event(create_pair( + std::make_pair(shid, pair_circle), + pid, p, partner_id, partner, (ipv_opposite * -1.0), len_ipv)); + } + } + SGFRD_TRACE(tracer_.write(""pair shell size = %1%, min_shell_size = %2%"", + pair_shell_size, sh_minim);) + SGFRD_TRACE(tracer_.write(""min-pair-intruder exists. multi should be formed"")) + return boost::none; +} + +DomainID SGFRDSimulator::form_multi( + const ParticleID& pid, const Particle& p, const FaceID& fid, + const std::vector >& doms) +{ + SGFRD_SCOPE(us, form_multi, tracer_); + + // here, `new_multi` is not initialized with particles yet, so the delta_t + // is negative. we need to update it after determine dt and reaction_length. + Multi new_multi(create_empty_multi()); + const DomainID formed_multi_id = this->add_event(new_multi); + + Multi& formed_multi = + boost::get(get_event(formed_multi_id)->domain()); + SGFRD_TRACE(tracer_.write(""new multi(%1%) created"", formed_multi_id)) + + const domain_id_setter didset(formed_multi_id); + + auto minsh = create_minimum_single_shell(pid, p, fid); + const Real new_shell_radius = minsh.second.size(); + formed_multi.add_particle(pid); + formed_multi.add_shell(minsh.first); + + SGFRD_TRACE(tracer_.write(""particle (%1%) and shell (%2%) is added to multi"", + pid, minsh.first)); + + DomainID did; Real dist; + for(const auto& didd : doms) + { + std::tie(did, dist) = didd; + + SGFRD_SCOPE(us, intruder_domain, tracer_); + SGFRD_TRACE(tracer_.write(""for domain %1%"", did)); + + if(dist < new_shell_radius) // add the domain to new multi + { + auto ev = get_event(did); + if(ev->which_domain() == event_type::multi_domain) + { + SGFRD_TRACE(tracer_.write(""domain (%1%) is multi. merging it..."", did)) + merge_multi(boost::get(ev->domain()), formed_multi); + } + else if(ev->which_domain() == event_type::pair_domain) + { + throw std::logic_error(""pair event cannot join to multi""); + } + else + { + SGFRD_TRACE(tracer_.write(""domain (%1%) is single. adding it..."", did)) + + // update shell with min_single_circular_shell! + ParticleID pid_; Particle p_; + std::tie(pid_, p_) = + boost::get(ev->domain()).particle_id_pair(); + const ShellID sid = boost::get(ev->domain()).shell_id(); + SGFRD_TRACE(tracer_.write(""domain (%1%) has particle(%2%), shell(%3%)"", + did, pid_, sid)); + + // edit shell size to be min_shell_radius. + circular_shell_type clsh = + boost::get(get_shell(sid)); + clsh.shape().size() = + calc_min_single_circular_shell_radius(p_); + clsh.domain_id() = formed_multi_id; + this->update_shell(sid, clsh, clsh.structure_id()); + SGFRD_TRACE(tracer_.write(""shell(%1%) size updated to %2%."", + sid, clsh.shape().size())); + + formed_multi.add_particle(pid_); + formed_multi.add_shell(sid); + + remove_event(did); + } + } + } + mut_sh_vis_applier(didset, formed_multi); + + // search intruders on the new multi, burst them all and add to multi if needed + add_to_multi_recursive(formed_multi); + formed_multi.determine_parameters(); + + // update multi domain assigned in scheduler; + // when the multi domain is assigned, it had a negative delta t. + // we need to update the data after determining delta_t and reaction_length. + this->scheduler_.update(std::make_pair(formed_multi_id, + std::make_shared(this->time() + formed_multi.dt(), formed_multi))); + + return formed_multi_id; +} + +void SGFRDSimulator::add_to_multi_recursive(Multi& multi_to_join) +{ + SGFRD_SCOPE(us, add_to_multi_recursive, tracer_); + + const Real tm = this->time(); + bool multi_enlarged = false; + const DomainID multi_to_join_id = get_domain_id(multi_to_join); + const domain_id_setter didset(multi_to_join_id); + + SGFRD_TRACE(tracer_.write(""add domain to multi %1% "", multi_to_join_id)); + + for(const ShellID& sid : multi_to_join.shell_ids()) + { + // assuming multi has only a circular_shell... + const auto& sh = boost::get(get_shell(sid)); + auto sh_pos = std::make_pair(sh.position(), sh.structure_id()); + const auto intruder = get_intrusive_domains( + std::make_pair(sh.position(), sh.structure_id()), sh.size()); + SGFRD_TRACE(tracer_.write( + ""intrusive domains on shell(%1%) are collected(size = %2%)"", + sid, intruder.size())); + + DomainID did; + for(const auto& didd : intruder) + { + std::tie(did, std::ignore) = didd; + if(did == multi_to_join_id){continue;} + + SGFRD_TRACE(tracer_.write(""bursting domain(%1%)"", did)); + auto ev = get_event(did); + + if(ev->which_domain() == event_type::multi_domain) + { + SGFRD_TRACE(tracer_.write(""intruder is multi. merge."")) + merge_multi(boost::get(ev->domain()), multi_to_join); + multi_enlarged = true; + } + else + { + SGFRD_TRACE(tracer_.write(""intruder is not multi. burst."")) + ParticleID pid; Particle p; FaceID fid; + for(const auto& pidpf : burst_event(std::make_pair(did, ev), tm)) + { + std::tie(pid, p, fid) = pidpf; + const Real dist = ecell4::polygon::distance(this->polygon(), + sh_pos, std::make_pair(p.position(), fid) + ) - sh.size() - p.radius(); + const Real min_shell_radius = + calc_min_single_circular_shell_radius(p); + if(dist < min_shell_radius) + { + SGFRD_TRACE(tracer_.write(""add the particle to multi"")) + + // assign new shell to shell_container and return its ID. + auto minsh = create_minimum_single_shell(pid, p, fid); + + multi_to_join.add_particle(pid); + multi_to_join.add_shell(minsh.first); + + // In the next loop, next shell may find this shell. + // and if so, the domain_id would not be initialized. + mut_sh_vis_applier(didset, multi_to_join); +// boost::get(this->get_shell(minsh.first)).domain_id() = multi_to_join_id; + + multi_enlarged = true; + } + else // enough distant. add closely-fitted shell + { + SGFRD_TRACE(tracer_.write(""add tight shell to the particle"")) + add_event(create_tight_domain( + create_tight_shell(pid, p, this->get_face_id(pid)), + pid, p)); + } + } + remove_event(did); + } + } + } + if(multi_enlarged) + { + mut_sh_vis_applier(didset, multi_to_join); + add_to_multi_recursive(multi_to_join); + } + + return; +} + +expected > > +SGFRDSimulator::form_single_conical_event( + const ParticleID& pid, const Particle& p, const FaceID fid) +{ + SGFRD_SCOPE(us, form_single_conical_event, tracer_); + + // create_event should handle D == 0 case. + assert(p.D() != 0.0); + + const std::pair pos = std::make_pair(p.position(), fid); + const std::vector > intrusive_vertices( + get_intrusive_vertices(pos, std::numeric_limits::infinity())); + + const VertexID& vid = intrusive_vertices.front().first; + + if(this->polygon().apex_angle_at(vid) > boost::math::constants::two_pi()) + { + // the apex locates around a saddle point or something like that. + // use Multi as a callback. + return err(std::vector >(0)); + } + + const Real dist_to_v = intrusive_vertices.front().second; + SGFRD_TRACE(tracer_.write(""vertex id = %1%, distance = %2%"", vid, dist_to_v)); + + const Real min_cone_size = (p.radius() + dist_to_v) * + single_conical_surface_shell_factor; + const Real max_cone_size = get_max_cone_size(vid); + SGFRD_TRACE(tracer_.write(""min_cone_size = %1%, max_cone_size = %2%"", + min_cone_size, max_cone_size)); + + if(min_cone_size > max_cone_size) + { + // cannot form cone nor circle. use multi. + return err(std::vector >(0)); + } + + const std::vector > intrusive_domains( + get_intrusive_domains(vid, max_cone_size)); + SGFRD_TRACE(tracer_.write(""intrusive_domain_size = %1%"", intrusive_domains.size())); + + if(intrusive_domains.empty()) + { + return ok(add_event(create_single( + create_single_conical_surface_shell(vid, max_cone_size), pid, p))); + } + + Real dist_to_max_shell_intruder = max_cone_size; + std::vector > min_shell_intruder; + for(std::vector >::const_iterator + iter = intrusive_domains.begin(), iend = intrusive_domains.end(); + iter != iend; ++iter) + { + // here, it calculates the distance between domain edges and the vertex. + // the value `iter->second` is not the distance between particles, + // it is a distance between domain and vertex. + // + // So it is not a problem that the value `iter->second` is shorter than + // the raidus of the particle. + + if(iter->second <= min_cone_size) + { + SGFRD_TRACE(tracer_.write(""%1% <= %2%, min shell intruder found!"", + iter->second, min_cone_size)); + min_shell_intruder.push_back(*iter); + } + else + { + // XXX because `intrusive_domains` are sorted by comparing the + // distance to them, once we found the element is far away, all + // the successors are much further. + dist_to_max_shell_intruder = + std::min(iter->second, dist_to_max_shell_intruder); + break; + } + } + + if(min_shell_intruder.empty()) + { + SGFRD_TRACE( + tracer_.write(""intrusive domains exist but enough distant""); + for(std::size_t i=0; i > shrinked_or_multi = + burst_and_shrink_non_multis(vid, min_shell_intruder); + SGFRD_TRACE(tracer_.write(""close domains are bursted."")); + + if(shrinked_or_multi.front().second > min_cone_size) + { + SGFRD_TRACE( + tracer_.write(""after burst, no intruder exist in the min-range %1%"", + min_cone_size); + for(std::size_t i=0; ishell_container_.list_shells_within_radius( + std::make_pair(this->polygon().position_at(vid), vid), + shell_size).empty()) + { + std::cout << ""nearest shell: "" + << this->shell_container_.list_shells_within_radius( + std::make_pair(this->polygon().position_at(vid), vid), + shell_size).front().first.first << std::endl; + std::cout << ""distance: "" + << this->shell_container_.list_shells_within_radius( + std::make_pair(this->polygon().position_at(vid), vid), + shell_size).front().second << std::endl; + std::cout << ""shell size "" << shell_size << std::endl; + throw std::runtime_error(""shells overlap each other""); + } + } + + return ok(add_event(create_single( + create_single_conical_surface_shell(vid, shell_size), pid, p))); + } + + return err(shrinked_or_multi); +} + +expected > > +SGFRDSimulator::form_single_circular_event( + const ParticleID& pid, const Particle& p, const FaceID fid, + const Real max_circle_size) +{ + SGFRD_SCOPE(us, form_single_circular_event, tracer_); + SGFRD_TRACE(tracer_.write(""forming single domain for particle %1% r = %2%"", + pid, p.radius())); + // create_event should handle D == 0 case. + assert(p.D() != 0.0); + + const Real min_circle_size = p.radius() * single_circular_shell_factor; + const auto pos = std::make_pair(p.position(), fid); + + /* XXX:TAKE CARE! the distance in the element of intrusive_domains, typed * + * as `std::pair` is not a distance between particle and * + * shell, but a distance between center of particle and shell surface. */ + const auto intrusive_domains = get_intrusive_domains(pos, max_circle_size); + SGFRD_TRACE(tracer_.write( + ""intrusive_domain_size = %1%"", intrusive_domains.size())) + + if(intrusive_domains.empty()) + { + SGFRD_TRACE(tracer_.write(""no intrusive domains exists."")) + SGFRD_TRACE(tracer_.write( + ""creating single event; shell size = %1%"", max_circle_size)) + return ok(add_event(create_single( + create_single_circular_shell(pos, max_circle_size), pid, p))); + } + + Real distance_to_nearest = max_circle_size; //XXX nearest (but not intruder) + std::vector > min_shell_intruder; + for(const auto& did_dist : intrusive_domains) + { + SGFRD_TRACE(tracer_.write(""check domain %1%: distance = %2%"", + did_dist.first, did_dist.second)); + if(did_dist.second <= min_circle_size) + { + SGFRD_TRACE(tracer_.write(""%1% is inside of minimum circle size"", + did_dist.first)); + if(did_dist.second < p.radius()) + { + throw std::runtime_error(( + boost::format(""form_single_circular_event: nearest domain "" + ""%1% overlaps with particle %2%. distance from point = "" + ""%3%, radius = %4%"") % did_dist.first % pid % + did_dist.second % p.radius() + ).str()); + } + min_shell_intruder.push_back(did_dist); + // collect all the min-shell-intruders. + continue; + } + else + { + SGFRD_TRACE(tracer_.write( + ""%1% does not intersect with minimum circle"", did_dist.first)); + + // calculate modest distance if this one is a single domain. + std::shared_ptr ev(this->get_event(did_dist.first)); + if(ev->which_domain() == event_type::single_domain) + { + SGFRD_TRACE(tracer_.write(""calculating modest r."")) + const Single& sgl = boost::get(ev->domain()); + const Particle& nearest_p = sgl.particle(); + const shell_type& sh = this->get_shell(sgl.shell_id()); + const Real sh_size = boost::apply_visitor(shell_size_getter(), sh); + + SGFRD_TRACE(tracer_.write(""raw distance = %1%"", did_dist.second)) + SGFRD_TRACE(tracer_.write(""shell radius = %1%"", sh_size)) + SGFRD_TRACE(tracer_.write(""nearp radius = %1%"", nearest_p.radius())) + + const Real modest_dist = calc_modest_shell_size(p, nearest_p, + did_dist.second + sh_size - p.radius() - nearest_p.radius()); + distance_to_nearest = std::min(did_dist.second, modest_dist); + } + else // nearest domain is not a single domain. + { + distance_to_nearest = did_dist.second; + } + SGFRD_TRACE(tracer_.write(""distance_to_nearest = %1%"", + distance_to_nearest)); + + // XXX because `intrusive_domains` are sorted by their distance, + // from nearest to distant, all the rests are far away. + break; + } + } + + if(min_shell_intruder.empty()) + { + SGFRD_TRACE( + tracer_.write(""intrusive domains exists but enough distant""); + for(std::size_t i=0; i > shrinked_or_multi = + burst_and_shrink_non_multis(pid, p, fid, min_shell_intruder); + SGFRD_TRACE(tracer_.write(""min_shell_intruder domains are bursted"")) + + if(shrinked_or_multi.front().second > min_circle_size) + { + SGFRD_TRACE( + tracer_.write(""after burst, no intruders exist""); + for(std::size_t i=0; i pos = std::make_pair(p.position(), fid); + const Real shell_size = p.radius() * (1.0 + minimum_separation_factor); + + // check particle does not overlap with any others. + assert(get_intrusive_domains(pos, shell_size).empty()); + + // create_tight_shell makes domain that lasts for 0.0 tau. + // tight_shells are for particles that have just been added to the + // system or just been bursted. + return add_event(create_single( + create_single_circular_shell(pos, shell_size), pid, p)); + } + + const std::pair pos = std::make_pair(p.position(), fid); + + const Real min_circle_size = p.radius() * single_circular_shell_factor; + const Real max_circle_size = get_max_circle_size(pos); + + SGFRD_TRACE(tracer_.write(""min_circle_size = %1%, max_circle_size = %2%"", + min_circle_size, max_circle_size)); + + if(max_circle_size < min_circle_size)// draw conical shell + { + expected > + > single_conical = this->form_single_conical_event(pid, p, fid); + if(single_conical.is_ok()) + { + SGFRD_TRACE(tracer_.write(""single conical was successfully formed"")) + return single_conical.unwrap(); + } + else + { + STAT(stat_multi_reason.add_count(SingleConicalFailed);) + SGFRD_TRACE(tracer_.write(""single conical could not be formed"")) + SGFRD_TRACE(tracer_.write(""forming multi..."")) + return form_multi(pid, p, fid, single_conical.unwrap_error()); + } + } + else // draw circluar shell + { + expected > + > single_circular = + this->form_single_circular_event(pid, p, fid, max_circle_size); + if(single_circular.is_ok()) + { + SGFRD_TRACE(tracer_.write(""single circular was successfully formed"")) + return single_circular.unwrap(); + } + + SGFRD_TRACE(tracer_.write(""single circular could not be formed"")) + + const std::vector >& intruders = + single_circular.unwrap_error(); + + boost::optional pair_ = + this->form_pair(pid, p, fid, intruders); + if(pair_) + { + SGFRD_TRACE(tracer_.write(""pair circular was formed"")) + return *pair_; + } + STAT(stat_multi_reason.add_count(PairFailed);) + SGFRD_TRACE(tracer_.write(""forming multi..."")) + return form_multi(pid, p, fid, intruders); + } +} + +bool SGFRDSimulator::diagnosis() const +{//{{{ +// const boost::chrono::steady_clock::time_point start_ = +// boost::chrono::high_resolution_clock::now(); + + bool result = true; + // 1. check overlap between particles + // 2. check overlap between shells + // 3. check all the particles are inside of its shell + + auto particles = this->world_->list_particles(); + auto shells = this->shell_container_.list_shells(); + + // 1. + ParticleID pid; Particle p; + for(const auto& pidp : particles) + { + std::tie(pid, p) = pidp; + if(p.radius() > world_->estimated_possible_largest_particle_radius()) + { + std::cerr << ""ERROR: particle "" << pid << "" is too large compared "" + << ""to the widths of triangles ("" + << world_->estimated_possible_largest_particle_radius() + << "").\n""; + result = false; + } + + const FaceID fid = this->get_face_id(pid); + std::pair pos = std::make_pair(p.position(), fid); + + ParticleID _pid; Particle _p; + for(const auto& _pidp : particles) + { + std::tie(_pid, _p) = _pidp; + if(pid == _pid) {continue;} + const FaceID _fid = this->get_face_id(_pid); + const Real dist = this->world_->distance(pos, + std::make_pair(_p.position(), _fid)); + if(dist < p.radius() + _p.radius()) + { + result = false; + std::cerr << ""ERROR: particle "" << pid << "" and "" << _pid + << ""overlaps!\n""; + std::cerr << "" : distance = "" << dist << "" < sum of radii = "" + << p.radius() + _p.radius() << '\n'; + std::cerr << "" : particle "" << pid << "" has radius "" + << p.radius() << "" at "" << p.position() << "" on "" + << fid << '\n'; + std::cerr << "" : particle "" << _pid << "" has radius "" + << _p.radius() << "" at "" << _p.position() << "" on "" + << _fid << '\n'; + } + } + + if(!this->polygon().is_inside_of_boundary(p.position())) + { + std::cerr << ""ERROR: particle "" << pid << "" is outside of the boundary!\n""; + std::cerr << "" : position = "" << p.position() << "", boundary = "" << polygon().edge_lengths() << ""\n""; + result = false; + } + + const Triangle& tri = this->polygon().triangle_at(fid); + const Barycentric bary = ::ecell4::to_barycentric(p.position(), tri); + if(!is_inside(bary)) + { + std::cerr << ""ERROR: particle "" << pid << "" is not on the face "" << fid << ""\n""; + std::cerr << "" : position = "" << p.position() << "", face = "" << tri << ""\n""; + std::cerr << "" : barycentric = "" << bary << "", face = "" << tri << ""\n""; + result = false; + } + } + + // 2. + ShellID shid; shell_type sh; + for(const auto& shidsh : shells) + { + std::tie(shid, sh) = shidsh; + ShellID _shid; shell_type _sh; + switch(sh.which()) + { + case shell_container_type::circular_shell: + { + circular_shell_type ccl = boost::get(sh); + distance_calculator_on_surface + dist_calc(ccl.get_surface_position(), this->polygon()); + + for(const auto& _shidsh : shells) + { + std::tie(_shid, _sh) = _shidsh; + if(_shid == shid){continue;} + const Real dist = boost::apply_visitor(dist_calc, _sh); + const DomainID _did = boost::apply_visitor(domain_id_getter(), _sh); + if(dist < ccl.size() && ccl.domain_id() != _did) + { + result = false; + std::cerr << ""ERROR: circular shell "" << shid + << "" and shell "" << _shid << ""overlaps\n""; + std::cerr << "" : distance = "" << dist - ccl.size() + << '\n'; + std::cerr << shid << "" -> "" << sh << '\n'; + std::cerr << _shid << "" -> "" << _sh << '\n'; + } + } + break; + } + case shell_container_type::conical_shell: + { + conical_surface_shell_type con = + boost::get(sh); + distance_calculator_on_surface + dist_calc(con.get_surface_position(), this->polygon()); + + for(const auto& _shidsh : shells) + { + std::tie(_shid, _sh) = _shidsh; + if(_shid == shid){continue;} + const Real dist = boost::apply_visitor(dist_calc, _sh); + const DomainID _did = boost::apply_visitor( + domain_id_getter(), _sh); + if(dist < con.size() && con.domain_id() != _did) + { + result = false; + std::cerr << ""ERROR: conical shell "" << shid + << "" and shell "" << _shid << ""overlaps\n""; + std::cerr << "" : distance = "" << dist - con.size() + << ""\n""; + std::cerr << shid << "" -> "" << sh << '\n'; + std::cerr << _shid << "" -> "" << _sh << '\n'; + } + } + break; + } + default: + { + result = false; + std::cerr << ""ERROR: shell "" << shid + << "" has invalid which() value "" << sh.which() << '\n'; + break; + } + } + } + + // 3. + std::map pid2evid; + std::map sid2evid; + EventID evid; std::shared_ptr ev_ptr; + for(const auto& evidptr : this->scheduler_.events()) + { + std::tie(evid, ev_ptr) = evidptr; + SGFRDEvent::domain_type const& dom = ev_ptr->domain(); + switch(ev_ptr->which_domain()) + { + case event_type::single_domain: + { + const Single& sgl = boost::get(dom); + const ShellID _shid = sgl.shell_id(); + const ParticleID _pid = sgl.particle_id(); + + if(pid2evid.count(_pid) == 0){pid2evid[_pid] = evid;} + if(sid2evid.count(_shid) == 0){sid2evid[_shid] = evid;} + + auto found_p = std::find_if(particles.begin(), particles.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(_pid)); + if(found_p == particles.end()) + { + result = false; + std::cerr << ""ERROR: particle might assigned to two "" + << ""different domains\n""; + std::cerr << "" : Single domain "" << evid << "" has particle "" + << _pid << "" but the particle is already erased\n""; + if(pid2evid.count(_pid) == 1) + { + std::cerr << "" : event "" << pid2evid[_pid] + << "" has particle "" << _pid << '\n'; + } + break; + } + auto found_s = std::find_if(shells.begin(), shells.end(), + ecell4::utils::pair_first_element_unary_predicator< + ShellID, shell_type>(_shid)); + if(found_s == shells.end()) + { + result = false; + std::cerr << ""ERROR: shell might assigned to two"" + << ""different domains\n""; + std::cerr << "" : Single domain "" << evid << "" has shell "" + << _shid << "" but the shell is already erased\n""; + if(sid2evid.count(_shid) == 1) + { + std::cerr << "" : event "" << sid2evid[_shid] + << "" has shell "" << _shid << '\n'; + } + + break; + } + const FaceID fid_p = this->get_face_id(_pid); + + distance_calculator_on_surface dist_calc( + std::make_pair(found_p->second.position(), fid_p), + this->polygon()); + + const Real dist = boost::apply_visitor(dist_calc, found_s->second) + + found_p->second.radius(); + if(dist > minimum_separation_factor) + { + result = false; + std::cerr << ""ERROR: particle is not inside of the Single (ID="" + << evid << "")\n""; + std::cerr << "" : shell size = "" + << boost::apply_visitor(shell_size_getter(), found_s->second) + << '\n'; + std::cerr << "" : shell pos = "" + << boost::apply_visitor(shell_position_getter(), found_s->second) + << '\n'; + std::cerr << "" : particle pos = "" << found_p->second.position() + << '\n'; + std::cerr << "" : dist - r_shell + r_particle = "" << dist + << '\n'; + } + + particles.erase(found_p); + shells.erase(found_s); + break; + } + case event_type::pair_domain: + { + const Pair& pr = boost::get(dom); + const ShellID _shid = pr.shell_id(); + const ParticleID _pid0 = pr.particle_id_at(0); + const ParticleID _pid1 = pr.particle_id_at(1); + if(pid2evid.count(_pid0) == 0){pid2evid[_pid0] = evid;} + if(pid2evid.count(_pid1) == 0){pid2evid[_pid1] = evid;} + if(sid2evid.count(_shid) == 0){sid2evid[_shid] = evid;} + + auto found_p0 = std::find_if(particles.begin(), particles.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(_pid0)); + if(found_p0 == particles.end()) + { + result = false; + std::cerr << ""ERROR: particle might assigned to two"" + << ""different domains\n""; + std::cerr << "" : Pair domain "" << evid << "" has particle "" + << _pid0 << "" but the particle is already erased\n""; + if(pid2evid.count(_pid0) == 1) + { + std::cerr << "" : event "" << pid2evid[_pid0] + << "" has particle "" << _pid0 << '\n'; + } + break; + } + auto found_p1 = std::find_if(particles.begin(), particles.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(_pid1)); + if(found_p1 == particles.end()) + { + result = false; + std::cerr << ""ERROR: particle might assigned to two"" + << ""different domains\n""; + std::cerr << "" : Pair domain "" << evid << "" has particle "" + << _pid1 << "" but the particle is already erased\n""; + if(pid2evid.count(_pid1) == 1) + { + std::cerr << "" : event "" << pid2evid[_pid1] + << "" has particle "" << _pid1 << '\n'; + } + break; + } + auto found_s = std::find_if(shells.begin(), shells.end(), + ecell4::utils::pair_first_element_unary_predicator< + ShellID, shell_type>(_shid)); + if(found_s == shells.end()) + { + result = false; + std::cerr << ""ERROR: shell might assigned to two"" + << ""different domains\n""; + std::cerr << "" : Pair domain "" << evid << "" has shell "" + << _shid << "" but the shell is already erased\n""; + if(sid2evid.count(_shid) == 1) + { + std::cerr << "" : event "" << sid2evid[_shid] + << "" has shell "" << _shid << '\n'; + } + break; + } + const FaceID fid_p0 = this->get_face_id(_pid0); + const FaceID fid_p1 = this->get_face_id(_pid1); + + if(found_s->second.which() != shell_container_type::circular_shell) + { + result = false; + std::cerr << ""ERROR: currently, pair is only for circular\n""; + std::cerr << "" : domain "" << evid << ""has shell "" << _shid + << "", but it has invalid shape "" << found_s->second.which() + << '\n'; + break; + } + + distance_calculator_on_surface + dist_calc0(std::make_pair(found_p0->second.position(), fid_p0), + this->polygon()); + distance_calculator_on_surface + dist_calc1(std::make_pair(found_p1->second.position(), fid_p1), + this->polygon()); + + const Real dist0 = boost::apply_visitor(dist_calc0, found_s->second) + + found_p0->second.radius(); + const Real dist1 = boost::apply_visitor(dist_calc1, found_s->second) + + found_p1->second.radius(); + if(dist0 > 0) + { + result = false; + std::cerr << ""ERROR: particle "" << _pid0 + << "" is not inside of the Pair "" << evid << ""\n""; + std::cerr << "" : dist - r_shell + r_particle = "" << dist0 + << '\n'; + } + if(dist1 > 0) + { + result = false; + std::cerr << ""ERROR: particle "" << _pid1 + << "" is not inside of the Pair "" << evid << ""\n""; + std::cerr << "" : dist - r_shell + r_particle = "" << dist1 + << '\n'; + } + particles.erase(found_p0); + // to avoid iterator break + found_p1 = std::find_if(particles.begin(), particles.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(_pid1)); + particles.erase(found_p1); + shells.erase(found_s); + break; + } + case event_type::multi_domain: + { + const Multi& mul = boost::get(dom); + ShellID _shid; + ParticleID _pid; Particle _p; + for(const auto& pidp : mul.particles()) + { + std::tie(_pid, _p) = pidp; + if(pid2evid.count(_pid) == 0){pid2evid[_pid] = evid;} + bool within = false; + auto found_p = std::find_if(particles.begin(), particles.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(_pid)); + if(found_p == particles.end()) + { + result = false; + std::cerr << ""ERROR: particle might assigned to two "" + << ""different domains\n""; + std::cerr << "" : domain "" << evid << "" has particle "" + << _pid << "" but the particle is already erased\n""; + if(pid2evid.count(_pid) == 1) + { + std::cerr << "" : event "" << pid2evid[_pid] + << "" has particle "" << _pid << '\n'; + } + continue; + } + const FaceID fid_p = this->get_face_id(_pid); + distance_calculator_on_surface + dist_calc(std::make_pair(found_p->second.position(), fid_p), + this->polygon()); + + for(const auto& _shid : mul.shell_ids()) + { + auto found_s = std::find_if(shells.begin(), shells.end(), + ecell4::utils::pair_first_element_unary_predicator< + ShellID, shell_type>(_shid)); + if(found_s == shells.end()) + { + result = false; + std::cerr << ""ERROR: shell might assigned to two "" + << ""different domains\n""; + std::cerr << "" : Multi domain "" << evid << "" has shell "" + << _shid << "" but the shell is already erased\n""; + continue; + } + const Real dist = + boost::apply_visitor(dist_calc, found_s->second) + + found_p->second.radius(); + if(dist < 0) + { + within = true; + } + } + + if(!within) + { + result = false; + std::cerr << ""ERROR: particle is not inside of any multi shell!\n""; + std::cerr << ""PID = "" << _pid << "", DID = "" << evid << '\n'; + } + particles.erase(found_p); + } + for(const auto& _shid : mul.shell_ids()) + { + if(sid2evid.count(_shid) == 0){sid2evid[_shid] = evid;} + + auto found_s = std::find_if(shells.begin(), shells.end(), + ecell4::utils::pair_first_element_unary_predicator< + ShellID, shell_type>(_shid)); + if(found_s == shells.end()) + { + result = false; + std::cerr << ""ERROR: shell might assigned to two"" + << ""different domains\n""; + std::cerr << "" : Multi domain "" << evid << "" has shell "" + << _shid << "" but the shell is already erased\n""; + if(sid2evid.count(_shid) == 1) + { + std::cerr << "" : event "" << sid2evid[_shid] + << "" has shell "" << _shid << '\n'; + } + continue; + } + shells.erase(found_s); + } + break; + } + case event_type::birth_domain: + { +// std::cerr << ""INFO : birth_domain is assigned\n""; + break; + } + default: + { + result = false; + std::cerr << ""ERROR: event "" << evid + << "" has invalid domain_kind "" << ev_ptr->which_domain() + << '\n'; + break; + } + } + } + + if(!particles.empty()) + { + result = false; + std::cerr << ""ERROR: some of particles are not assigned to Domain\n""; + for(const auto& pidp : particles) + { + std::tie(pid, p) = pidp; + std::cerr << "" : particle id "" << pid + << "" is not assigned to any Domain\n""; + } + } + if(!shells.empty()) + { + result = false; + std::cerr << ""ERROR: some of shells are not assigned to Domain\n""; + for(const auto& shidsh : shells) + { + std::tie(shid, sh) = shidsh; + std::cerr << "" : shell id "" << shid + << "" is not assigned to any Domain\n""; + const DomainID _did = boost::apply_visitor(domain_id_getter(), sh); + std::cerr << "" : it should be contained by "" << _did << '\n'; + } + } + if(result) + { +// const boost::chrono::steady_clock::time_point end_ = +// boost::chrono::high_resolution_clock::now(); + std::cerr << ""time = "" << this->time() << "" simulator is sanitized.\n""; +// << ""it took "" << static_cast(boost::chrono::duration_cast< +// boost::chrono::milliseconds>(end_ - start_).count()) / 1e3 +// << "" seconds.\n""; + } + std::cerr << std::flush; + return result; +}// }}} + +} // sgfrd +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/tracer.hpp",".hpp","7042","191","#ifndef ECELL4_SGFRD_TRACER +#define ECELL4_SGFRD_TRACER +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +template > +class basic_tracer; + +template<> +class basic_tracer > +{ + public: + typedef char char_type; + typedef std::char_traits traits_type; + + public: + basic_tracer(const std::string& fname) + : indent_size_(2), indent_(0), current(0) + { + fnames[0] = fname + std::string(""01.log""); + fnames[1] = fname + std::string(""02.log""); + } + basic_tracer(const std::string& fname, const std::size_t indent_size) + : indent_size_(indent_size), indent_(0), current(0) + { + fnames[0] = fname + std::string(""01.log""); + fnames[1] = fname + std::string(""02.log""); + } + ~basic_tracer(){} + + void indent() throw() {indent_ += 1; return;} + void unindent() throw() {indent_ -= 1; return;} + + void clear() + { + std::ofstream f0(fnames[0].c_str()); f0.close(); + std::ofstream f1(fnames[1].c_str()); f1.close(); + } + + void write(const std::string& tr) + { + { + std::ofstream ofs(fnames.at(current).c_str(), + std::ios_base::in | std::ios_base::out | std::ios_base::ate); + const std::string idt(indent_size_ * indent_, ' '); + ofs << idt << tr << std::endl; + ofs.close(); + } + + std::ifstream ifs(fnames.at(current).c_str()); + ifs.seekg(0, std::ios::beg); + std::ifstream::streampos init = ifs.tellg(); + ifs.seekg(0, std::ios::end); + std::ifstream::streampos last = ifs.tellg(); + ifs.close(); + + std::ifstream::streampos sz = last - init; + if(sz > 50000000) + { + current = (current == 0) ? 1 : 0; + // clear the next file + std::ofstream nxt(fnames.at(current).c_str(), std::ios_base::trunc); + nxt.close(); + } + return; + } + + template + void write(const formT& tr, const T1& a1) + { + this->write((boost::format(tr) % a1).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2) + { + this->write((boost::format(tr) % a1 % a2).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3) + { + this->write((boost::format(tr) % a1 % a2 % a3).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4 % a5).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4 % a5 % a6).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4 % a5 % a6 % a7).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4 % a5 % a6 % a7 % a8).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4 % a5 % a6 % a7 % a8 % a9).str()); + } + template + void write(const formT& tr, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10) + { + this->write((boost::format(tr) % a1 % a2 % a3 % a4 % a5 % a6 % a7 % a8 % a9 % a10).str()); + } + + private: + std::size_t indent_size_; + std::size_t indent_; + std::size_t current; + std::array fnames; +}; + +typedef basic_tracer > tracer; + +template > +class scope +{ + public: + typedef charT char_type; + typedef traitsT traits_type; + typedef basic_tracer tracer_type; + + public: + scope(tracer_type& trc) + : tracer_(trc), name_("""") + { + tracer_.write(""{""); + tracer_.indent(); + } + scope(tracer_type& trc, const std::string& name) + : tracer_(trc), name_(name) + { + tracer_.write(""%s {"", name_); + tracer_.indent(); + } + ~scope() + { + tracer_.unindent(); + tracer_.write(""}""); + } + + std::string const& name() const throw() {return name_;} + + private: + tracer_type& tracer_; + const std::string name_; +}; + +typedef scope > scope_ns; +typedef scope > scope_us; +typedef scope > scope_ms; +typedef scope > scope_s; +typedef scope > scope_m; +typedef scope > scope_h; + +/* ----------------------------- scope impl end ----------------------------- */ + +#ifndef ECELL4_SGFRD_NO_TRACE +#define SGFRD_TRACE(x) x; +#define SGFRD_SCOPE(time, name, trc) BOOST_PP_CAT(scope_, time) BOOST_PP_CAT(scope_, name)(trc, BOOST_PP_STRINGIZE(name)); +#else //ECELL4_SGFRD_NO_TRACE +#define SGFRD_TRACE(x) /**/ +#define SGFRD_SCOPE(time, name, trc) /**/ +#endif//ECELL4_SGFRD_NO_TRACE + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_TRACER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/StructureRegistrator.hpp",".hpp","5121","163","#ifndef ECELL4_SGFRD_STRUCTURE_REGISTRATOR +#define ECELL4_SGFRD_STRUCTURE_REGISTRATOR +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +template +struct StructureRegistrator +{ +public: + + typedef T_element_id element_id_type; + typedef T_structure_id structure_id_type; + typedef std::vector element_id_array_type; + typedef std::unordered_map container_type; + typedef std::unordered_map elemid_to_strid_map_type; + + typedef typename container_type::iterator iterator; + typedef typename container_type::const_iterator const_iterator; + typedef ecell4::Polygon polygon_type; +public: + + StructureRegistrator() = default; + ~StructureRegistrator() = default; + + void emplace(const element_id_type&, const structure_id_type&); // add new relation + void update (const element_id_type&, const structure_id_type&); // remove old relation and add new one + void remove (const element_id_type&, const structure_id_type&); // use hint + void remove (const element_id_type& eid) + { + this->remove(eid, elemid_to_strid_map_.at(eid)); + return ; + } + + bool have(const element_id_type& eid) const + { + return elemid_to_strid_map_.count(eid) != 0; + } + + element_id_array_type& elements_over(const structure_id_type& sid) + { + return container_.at(sid); + } + element_id_array_type const& elements_over(const structure_id_type& sid) const + { + return container_.at(sid); + } + structure_id_type& structure_on(const element_id_type& eid) + { + return elemid_to_strid_map_.at(eid); + } + structure_id_type const& structure_on(const element_id_type& eid) const + { + return elemid_to_strid_map_.at(eid); + } + + void reset(){elemid_to_strid_map_.clear(); container_.clear();} + bool empty() const throw() {return container_.empty();} + std::size_t size() const throw() {return container_.size();} + void resize(std::size_t i){return container_.resize(i);} + + iterator begin() throw() {return container_.begin();} + iterator end() throw() {return container_.begin();} + const_iterator begin() const throw() {return container_.begin();} + const_iterator end() const throw() {return container_.end();} + const_iterator cbegin() const throw() {return container_.begin();} + const_iterator cend() const throw() {return container_.end();} + + void dump(std::ostream& os) const; + +protected: + + elemid_to_strid_map_type elemid_to_strid_map_; //ex {pID -> fID} + container_type container_; // {fid -> {pid,...}, ...} +}; + + +template +void StructureRegistrator::emplace( + const element_id_type& eid, const structure_id_type& sid) +{ + if(this->have(eid)) + { + throw std::logic_error(""already have""); + } + elemid_to_strid_map_[eid] = sid; + + if(container_.count(sid) == 0) + { + container_[sid] = element_id_array_type{}; + } + container_[sid].push_back(eid); + return; +} + +template +void StructureRegistrator::update( + const element_id_type& eid, const structure_id_type& sid) +{ + // remove older eid-sid relationship + const structure_id_type old_sid = elemid_to_strid_map_[eid]; + element_id_array_type& old_value = container_[old_sid]; + + const auto found = std::find(old_value.begin(), old_value.end(), eid); + assert(found != old_value.end()); // should be found + old_value.erase(found); + + // add new relationship + elemid_to_strid_map_[eid] = sid; + if(container_.count(sid) == 0) + { + container_[sid] = element_id_array_type{}; + } + container_[sid].push_back(eid); + return; +} + +template +void StructureRegistrator::remove( + const element_id_type& eid, const structure_id_type& sid) +{ + element_id_array_type& old_value = container_[sid]; + + const auto found = std::find(old_value.begin(), old_value.end(), eid); + assert(found != old_value.end()); + old_value.erase(found); + + elemid_to_strid_map_.erase(eid); + return; +} + +template +void StructureRegistrator::dump(std::ostream& os) const +{ +// elemid_to_strid_map_type elemid_to_strid_map_; //ex {pID -> fID} +// container_type container_; //ex {, ...} + os << ""StructureRegistrator::dump\n""; + os << ""{element ID -> structure ID}\n""; + for(const auto& eid_sid : this->elemid_to_strid_map_) + { + os << ""{ "" << eid_sid.first << "" -> "" << eid_sid.second << "" }\n""; + } + os << std::endl; + + os << ""{structure ID -> {list of elements...}}\n""; + for(const auto& sid_es : this->container_) + { + os << ""{ "" << sid_es.first << "" -> { ""; + for(const auto& eid : sid_es.second) {os << eid << ' ';} + os << ""}}\n""; + } + os << std::endl; + return ; +} + +} // sgfrd +} // ecell4 +#endif // ECELL4_SGFRD_STRUCTURE_REGISTRATOR +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/SGFRDWorld.hpp",".hpp","28603","851","#ifndef ECELL4_SGFRD_WORLD +#define ECELL4_SGFRD_WORLD +#include ""StructureRegistrator.hpp"" +#include ""ReactionInfo.hpp"" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +struct MoleculeInfo +{ + const Real radius; + const Real D; +}; + +class SGFRDWorld + : public ecell4::WorldInterface +{ + public: + typedef ecell4::Polygon polygon_type; + typedef Barycentric barycentric_type; + + typedef ecell4::sgfrd::MoleculeInfo molecule_info_type; + typedef ecell4::Model model_type; + + typedef ParticleSpaceCellListImpl default_particle_space_type; + typedef ParticleSpace particle_space_type; + typedef particle_space_type::particle_container_type + particle_container_type; + typedef ecell4::SerialIDGenerator particle_id_generator_type; + typedef StructureRegistrator + structure_registrator_type; + + public: + + // !rng && !polygon_file + SGFRDWorld(const Real3& edge_lengths = Real3(1, 1, 1), + const Integer3& matrix_sizes = Integer3(3, 3, 3)) + : ps_(new default_particle_space_type(edge_lengths, matrix_sizes)), + polygon_(std::make_shared(edge_lengths, matrix_sizes)) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + rng_->seed(); + + this->prepare_restrictions(); + } + + // rng && !polygon_file + SGFRDWorld(const Real3& edge_lengths, const Integer3& matrix_sizes, + std::shared_ptr rng) + : ps_(new default_particle_space_type(edge_lengths, matrix_sizes)), + rng_(rng), + polygon_(std::make_shared(edge_lengths, matrix_sizes)) + { + this->prepare_restrictions(); + } + + // !rng && polygon_file + SGFRDWorld(const Real3& edge_lengths, const Integer3& matrix_sizes, + const std::string& polygon_file, const STLFormat fmt) + : ps_(new default_particle_space_type(edge_lengths, matrix_sizes)), + polygon_(std::make_shared( + read_polygon(polygon_file, fmt, edge_lengths))) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + rng_->seed(); + + this->prepare_restrictions(); + } + + // rng && polygon_file + SGFRDWorld(const Real3& edge_lengths, const Integer3& matrix_sizes, + std::shared_ptr rng, + const std::string& polygon_file, const STLFormat fmt) + : ps_(new default_particle_space_type(edge_lengths, matrix_sizes)), + rng_(rng), polygon_(std::make_shared( + read_polygon(polygon_file, fmt, edge_lengths))) + { + this->prepare_restrictions(); + } + + // !rng && polygon + SGFRDWorld(const Real3& edge_lengths, const Integer3& matrix_sizes, + const std::shared_ptr& poly) + : ps_(new default_particle_space_type(edge_lengths, matrix_sizes)), + polygon_(poly) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + rng_->seed(); + + this->prepare_restrictions(); + + write_polygon(""tmp.stl"", STLFormat::Ascii, *polygon()); + } + + // rng && polygon + SGFRDWorld(const Real3& edge_lengths, const Integer3& matrix_sizes, + std::shared_ptr rng, + const std::shared_ptr& poly) + : ps_(new default_particle_space_type(edge_lengths, matrix_sizes)), + rng_(rng), polygon_(poly) + { + this->prepare_restrictions(); + } + + SGFRDWorld(const std::string& filename) // from HDF5 + : ps_(new default_particle_space_type(Real3(1, 1, 1))), + polygon_(std::make_shared(Real3(1, 1, 1))) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + this->load(filename); + } + + + ~SGFRDWorld() override = default; + + std::shared_ptr const& rng() const noexcept {return this->rng_;} + std::shared_ptr& rng() noexcept {return this->rng_;} + std::shared_ptr const& polygon() const {return polygon_;} + + // ----------------------------------------------------------------------- + // WorldInterface + + const Real t() const override + { + return ps_->t(); + } + void set_t(const Real& t) override + { + return ps_->set_t(t); + } + + void save(const std::string& filename) const override + { +#ifdef WITH_HDF5 + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + rng_->save(fout.get()); + pidgen_.save(fout.get()); + + std::unique_ptr + group1(new H5::Group(fout->createGroup(""ParticleSpace""))); + ps_->save_hdf5(group1.get()); + + std::unique_ptr + group2(new H5::Group(fout->createGroup(""Polygon""))); + this->polygon_->save_hdf5(group2.get()); + + extras::save_version_information( + fout.get(), std::string(""ecell4-sgfrd-"") + std::string(VERSION_INFO)); + return; +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void load(const std::string& filename) override + { +#ifdef WITH_HDF5 + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-sgfrd-0.0""; + try + { + const std::string version = extras::load_version_information(*fin); + if (!extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required << ""] or later is required.""; + throw NotSupported(ss.str()); + } + } + catch(H5::GroupIException not_found_error) + { + throw NotFound(""No version information was found.""); + } + + const H5::Group group1(fin->openGroup(""ParticleSpace"")); + ps_->load_hdf5(group1); + + const H5::Group group2(fin->openGroup(""Polygon"")); + polygon_->load_hdf5(group2); + + pidgen_.load(*fin); + rng_->load(*fin); + + // restore polygon-particle relationships. + // -------------------------------------------------------------------- + // The above code reads 3D positions of particles. But the information + // about which particle is on which face are not restored. + // The nice thing is that all the restored particles locate precisely + // (within the limit of numerical error) on the faces unless the polygon + // shape was changed by restoring. + + for(auto pidp : this->list_particles()) + { + const auto& fp = this->find_face(pidp.second.position()); + if(!fp) + { + throw std::invalid_argument(""Particle does not locate on any face""); + } + pidp.second.position() = fp->first; + this->update_particle(pidp.first, pidp.second, fp->second); + } + return; +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + /** + * draw attributes of species and return it as a molecule info. + * @param sp a species + * @return info a molecule info + */ + MoleculeInfo get_molecule_info(const Species& sp) const + { + Real radius(0.0), D(0.0); + + if (std::shared_ptr bound_model = lock_model()) + { + auto const sp_ = bound_model->apply_species_attributes(sp); + if (sp_.has_attribute(""radius"")) + { + radius = sp_.get_attribute_as(""radius""); + } + if (sp_.has_attribute(""D"")) + { + D = sp_.get_attribute_as(""D""); + } + } + + { + if (sp.has_attribute(""radius"")) + { + radius = sp.get_attribute_as(""radius""); + } + if (sp.has_attribute(""D"")) + { + D = sp.get_attribute_as(""D""); + } + } + + if (radius <= 0.0) + { + std::stringstream msg; + msg << ""A particle with invalid size ["" << radius << ""] was given.""; + throw IllegalArgument(msg.str()); + } + + MoleculeInfo info = {radius, D}; + return info; + } + + const Real volume() const override + { + return ps_->volume(); + } + + bool has_species(const Species& sp) const override + { + for(auto&& item : ps_->list_species()) + { + if(item == sp){return true;} + } + return false; + } + + std::vector list_species() const override + { + return ps_->list_species(); + } + + Integer num_molecules(const Species& sp) const override + { + return ps_->num_molecules(sp); + } + + Integer num_molecules_exact(const Species& sp) const override + { + return ps_->num_molecules_exact(sp); + } + + Real get_value(const Species& sp) const override + { + return ps_->get_value(sp); + } + Real get_value_exact(const Species& sp) const override + { + return ps_->get_value_exact(sp); + } + + const Real3& edge_lengths() const override + { + return ps_->edge_lengths(); + } + + Integer num_particles() const override + { + return ps_->num_particles(); + } + Integer num_particles(const Species& sp) const override + { + return ps_->num_particles(sp); + } + Integer num_particles_exact(const Species& sp) const override + { + return ps_->num_particles_exact(sp); + } + + bool has_particle(const ParticleID& pid) const override + { + return ps_->has_particle(pid); + } + std::pair get_particle(const ParticleID& pid) const override + { + return ps_->get_particle(pid); + } + + std::pair + get_surface_position(const ParticleID& pid) const + { + const auto fid = this->registrator_.structure_on(pid); + const auto& tri = this->polygon_->triangle_at(fid); + const auto pos = this->ps_->get_particle(pid).second.position(); + return std::make_pair(fid, to_barycentric(pos, tri)); + } + + std::vector > + list_particles() const override + { + return ps_->list_particles(); + } + std::vector > + list_particles(const Species& sp) const override + { + return ps_->list_particles(sp); + } + std::vector > + list_particles_exact(const Species& sp) const override + { + return ps_->list_particles_exact(sp); + } + + std::vector>> + list_surface_positions() const + { + std::vector>> v; + v.reserve(this->num_particles()); + for(auto&& pp : this->list_particles()) + { + v.emplace_back(pp.first, this->get_surface_position(pp.first)); + } + return v; + } + std::vector>> + list_surface_positions(const Species& sp) const + { + std::vector>> v; + v.reserve(this->num_particles(sp)); + for(auto&& pp : this->list_particles(sp)) + { + v.emplace_back(pp.first, this->get_surface_position(pp.first)); + } + return v; + } + std::vector>> + list_surface_positions_exact(const Species& sp) const + { + std::vector>> v; + v.reserve(this->num_particles_exact(sp)); + for(auto&& pp : this->list_particles_exact(sp)) + { + v.emplace_back(pp.first, this->get_surface_position(pp.first)); + } + return v; + } + + // ----------------------------------------------------------------------- + // ParticleSpaceInterface + + std::pair, bool> + new_particle(const Particle& p); + std::pair, bool> + new_particle(const Particle& p, const FaceID& fid); + + std::pair, bool> + new_particle(const Species& sp, const Real3& pos) + { + const auto info = this->get_molecule_info(sp); + return this->new_particle(Particle(sp, pos, info.radius, info.D)); + } + std::pair, bool> + new_particle(const Species& sp, const FaceID& fid, const Barycentric& bary) + { + const auto info = this->get_molecule_info(sp); + + const auto& tri = this->polygon_->triangle_at(fid); + const auto pos = to_absolute(bary, tri); + + return this->new_particle(Particle(sp, pos, info.radius, info.D), fid); + } + std::pair, bool> + new_particle(const Species& sp, const std::pair& sfp) + { + return this->new_particle(sp, sfp.first, sfp.second); + } + + std::pair, bool> + throw_in_particle(const Species& sp); + + void add_molecules(const Species& sp, const Integer& num); + void add_molecules(const Species& sp, const Integer& num, + const std::shared_ptr shape); + + void remove_molecules(const Species& sp, const Integer& num) + { + if (num < 0) + { + throw std::invalid_argument( + ""The number of molecules must be positive.""); + } + + auto particles(list_particles(sp)); + const Integer num_particles(particles.size()); + if (num_particles < num) + { + throw std::invalid_argument( + ""The number of molecules cannot be negative.""); + } + + shuffle((*rng_), particles); + for (auto i(particles.begin()); i != particles.begin() + num; ++i) + { + remove_particle((*i).first); + } + return; + } + + bool update_particle(const ParticleID& pid, const Particle& p) + { + // Note: condition in `if` statements can have a declarator. + // cf. N3337 section 6.4 ""Selection statements"" + if(const auto pfid = this->find_face(p.position())) + { + Particle p_(p); + p_.position() = pfid->first; + + return this->update_particle(pid, p_, pfid->second); + } + throw std::invalid_argument(""[error] SGFRDWorld::update_particle: "" + ""particle locates distant from polygon""); + } + bool update_particle(const ParticleID& pid, const Particle& p, + const FaceID& fid) + { + if(registrator_.have(pid)) + { + registrator_.update(pid, fid); + } + else + { + registrator_.emplace(pid, fid); + } + return ps_->update_particle(pid, p); + } + + // this also removes particle if it is on surface + void remove_particle(const ParticleID& pid) + { + if(registrator_.have(pid)) + { + registrator_.remove(pid); + } + return ps_->remove_particle(pid); + } + void remove_particle(const ParticleID& pid, const FaceID& fid) + { + registrator_.remove(pid, fid); + return ps_->remove_particle(pid); + } + bool + has_particle(const FaceID& fid) const + { + return registrator_.elements_over(fid).size() > 0; + } + Integer + num_particle(const FaceID& fid) const + { + return registrator_.elements_over(fid).size(); + } + + Triangle get_triangle(const ParticleID& pid) const + { + return this->polygon_->triangle_at(this->registrator_.structure_on(pid)); + } + + std::vector > + list_particles(const FaceID& fid) const + { + const std::vector& pids = registrator_.elements_over(fid); + std::vector> retval(pids.size()); + + std::transform(pids.begin(), pids.end(), retval.begin(), + [this](const ParticleID& pid) -> std::pair { + return this->get_particle(pid); + }); + return retval; + } + std::vector const& + list_particleIDs(const FaceID& fid) const + { + return registrator_.elements_over(fid); + } + + bool is_on_face(const ParticleID& pid) const + { + return registrator_.have(pid); + } + + FaceID get_face_id(const ParticleID& pid) const + { + return registrator_.structure_on(pid); + } + + Real distance_sq(const Real3& lhs, const Real3& rhs) + { + const auto pf1 = this->find_face(lhs); + if(pf1) + { + const auto pf2 = this->find_face(rhs); + if(pf2) + { + return this->distance_sq(*pf1, *pf2); + } + } + throw std::invalid_argument(""[error] SGFRDWorld::distance_sq: "" + ""particle locates distant from polygon""); + } + Real distance(const Real3& lhs, const Real3& rhs) + { + const auto pf1 = this->find_face(lhs); + if(pf1) + { + const auto pf2 = this->find_face(rhs); + if(pf2) + { + return this->distance(*pf1, *pf2); + } + } + throw std::invalid_argument(""[error] SGFRDWorld::distance: "" + ""particle locates distant from polygon""); + } + + template + Real distance_sq(const std::pair& lhs, + const std::pair& rhs) + { + return ecell4::polygon::distance_sq(*polygon_, lhs, rhs); + } + template + Real distance(const std::pair& lhs, + const std::pair& rhs) + { + return ecell4::polygon::distance(*polygon_, lhs, rhs); + } + + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius) const + { + if(const auto pf = this->find_face(pos)) + { + return this->list_particles_within_radius(*pf, radius); + } + throw std::invalid_argument(""[error] "" + ""SGFRDWorld::list_particles_within_radius: "" + ""particle locates distant from polygon""); + } + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore) const + { + if(const auto pf = this->find_face(pos)) + { + return this->list_particles_within_radius(*pf, radius, ignore); + } + throw std::invalid_argument(""[error] "" + ""SGFRDWorld::list_particles_within_radius: "" + ""particle locates distant from polygon""); + } + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const + { + if(const auto pf = this->find_face(pos)) + { + return this->list_particles_within_radius( + *pf, radius, ignore1, ignore2); + } + throw std::invalid_argument(""[error] "" + ""SGFRDWorld::list_particles_within_radius: "" + ""particle locates distant from polygon""); + } + + // for 2D + std::vector, Real> > + list_particles_within_radius( + const std::pair& pos, const Real& radius) const; + std::vector, Real> > + list_particles_within_radius( + const std::pair& pos, const Real& radius, + const ParticleID& ignore) const; + std::vector, Real> > + list_particles_within_radius( + const std::pair& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const; + + std::vector > list_vertices_within_radius( + const std::pair& pos, const Real& radius) const + { + const Real threshold_sq = radius * radius; + std::vector > retval; + const std::vector candidates = + this->polygon_->neighbor_vertices_of(pos.second); + for(std::vector::const_iterator + i(candidates.begin()), e(candidates.end()); i!=e; ++i) + { + const VertexID vid = *i; + const Real dist_sq = ecell4::polygon::distance_sq(*(this->polygon_), + pos, std::make_pair(this->polygon_->position_at(vid), vid)); + if(dist_sq < threshold_sq) + { + retval.push_back(std::make_pair(vid, std::sqrt(dist_sq))); + } + } + std::sort(retval.begin(), retval.end(), + ecell4::utils::pair_second_element_comparator()); + return retval; + } + + // return false if overlap exists. for 3D. FIXME: speedup + bool check_no_overlap(const Real3& pos, const Real& radius) const + { + return this->list_particles_within_radius(pos, radius).empty(); + } + bool check_no_overlap(const Real3& pos, const Real& radius, + const ParticleID& ignore) const + { + return this->list_particles_within_radius(pos, radius, ignore).empty(); + } + bool check_no_overlap(const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const + { + return this->list_particles_within_radius(pos, radius, ignore1, ignore2 + ).empty(); + } + + // return false if overlap exists. + bool check_no_overlap( + const std::pair& pos, const Real& radius) const; + bool check_no_overlap( + const std::pair& pos, const Real& radius, + const ParticleID& ignore) const; + bool check_no_overlap( + const std::pair& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const; + + particle_container_type const& particles() const {return ps_->particles();} + + Real3 periodic_transpose(const Real3& pos1, const Real3& pos2) const + { + return this->polygon_->periodic_transpose(pos1, pos2); + } + Real3 apply_boundary(const Real3& pos) const + { + return this->ps_->apply_boundary(pos); + } + + void bind_to(std::shared_ptr model) + { + if (std::shared_ptr bound_model = lock_model()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to BDWorld"" + << std::endl; + } + } + model_ = model; + } + + std::shared_ptr lock_model() const + { + return model_.lock(); + } + + std::array const& barrier_at(const FaceID& fid) const + { + return this->barriers_.at(fid); + } + + Real estimated_possible_largest_particle_radius() const noexcept + { + return this->estimated_possible_largest_particle_radius_; + } + + private: + + // the tolerance is relative to edge_lengths. + boost::optional> + find_face(const Real3& pos, const Real tolerance = 1e-3) const + { + const auto& width = this->edge_lengths(); + const auto tol = tolerance * std::min(width[0], std::min(width[1], width[2])); + const auto tol2 = tol * tol; + + Real min_distance = std::numeric_limits::infinity(); + boost::optional> nearest = boost::none; + for(const auto& fid : this->polygon_->list_face_ids()) + { + const auto& tri = this->polygon_->triangle_at(fid); + const auto dist = + ecell4::collision::distance_sq_point_triangle(pos, tri); + if(dist <= tol2) + { + if(!nearest || dist < min_distance) + { + min_distance = dist; + nearest = std::make_pair(pos, fid); + } + } + } + return nearest; + } + + inline static Real3 normalize(const Real3& v) throw() + { + return v * (1.0 / std::sqrt(length_sq(v))); + } + + void prepare_restrictions() + { + // To avoid edge cases, it calculates the maximum size of particle. + // Also, to avoid overlap between shells, it calculates a bisector of + // each angle in triangle. + Real min_altitude = std::numeric_limits::max(); + for(const auto& fid : polygon_->list_face_ids()) + { + const auto& tri = polygon_->triangle_at(fid); + + // Estimate largest particle radius possible. + const auto S = tri.area(); + min_altitude = std::min(min_altitude, 2.0 * S / tri.length_of_edge_at(0)); + min_altitude = std::min(min_altitude, 2.0 * S / tri.length_of_edge_at(1)); + min_altitude = std::min(min_altitude, 2.0 * S / tri.length_of_edge_at(2)); + + // calculate boundary for shell size + const auto& edges = polygon_->edges_of(fid); + const auto& vtxs = polygon_->vertices_of(fid); + std::array segments; + for(std::size_t i=0; i<3; ++i) + { + // vi1 ei1 vi0 | + // <-----. | + // \ ^ \ | + // ei2 \ /ei0\ | + // v/_____\ | + // vi2 | + + const auto ei0 = polygon_->opposite_of(edges.at(i)); + const auto ei1 = polygon_->next_of(ei0); + const auto ei2 = polygon_->next_of(ei1); + const auto lei0 = polygon_->length_of(ei0); + const auto lei1 = polygon_->length_of(ei1); + const auto lei2 = polygon_->length_of(ei2); + const auto dei1 = polygon_->direction_of(ei1); + const auto dei2 = polygon_->direction_of(ei2); + + const auto vi0 = polygon_->target_of(ei0); + const auto vi1 = polygon_->target_of(ei1); + const auto vi2 = polygon_->target_of(ei2); + + assert(vi0 == vtxs[i]); + assert(vi2 == vtxs[i==2?0:i+1]); + + const auto pvi0 = tri.vertices()[i]; + const auto pvi1 = this->periodic_transpose(polygon_->position_at(vi1), pvi0); + const auto pvi2 = tri.vertices()[(i==2)?0:i+1]; + + const auto dst0 = pvi1 + dei2 * (lei1 / (lei1 + lei0)); + const auto dst2 = pvi0 + dei1 * (lei0 / (lei0 + lei2)); + + segments[2*i ] = Segment(dst0, pvi0); + segments[2*i+1] = Segment(dst2, pvi2); + } + this->barriers_[fid] = segments; + } + this->estimated_possible_largest_particle_radius_ = min_altitude * 0.5; + return; + } + + private: + + std::unique_ptr ps_; + std::shared_ptr rng_; + std::weak_ptr model_; + std::shared_ptr polygon_; + structure_registrator_type registrator_; + particle_id_generator_type pidgen_; + Real estimated_possible_largest_particle_radius_; + + // this contains the edges that correspond to the developed neighbor faces. + // + // /\ + // > /__\ < + // /\* /\ + // > /__\/__\ < these edges + // ^ ^ + boost::container::flat_map > barriers_; +}; + + +}// sgfrd +}// ecell4 +#endif // ECELL4_SGFRD_WORLD +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/SGFRDEvent.hpp",".hpp","1356","61","#ifndef ECELL4_SGFRD_EVENT +#define ECELL4_SGFRD_EVENT +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +struct SGFRDEvent +{ +public: + typedef boost::variant domain_type; + + enum domain_kind + { + single_domain = 0, + pair_domain = 1, + multi_domain = 2, + birth_domain = 3, + // std::numeric_limits::max() is not constexpr in c++03. + invalid = INT_MAX, + }; + +public: + + template + SGFRDEvent(Real const& time, const domainT& dom) + : time_(time), domain_(dom) + {} + + Real const& time() const {return time_;} + domain_type const& domain() const {return domain_;} + domain_type & domain() {return domain_;} + + domain_kind which_domain() const + { + return static_cast(domain_.which()); + } + +private: + + Real time_; + domain_type domain_; +}; + +typedef ecell4::EventSchedulerBase SGFRDEventScheduler; +typedef SGFRDEventScheduler::identifier_type EventID; +typedef EventID DomainID; // XXX! + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_EVENT +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/Shell.hpp",".hpp","1893","69","#ifndef ECELL4_SGFRD_SHELL +#define ECELL4_SGFRD_SHELL +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +template +class Shell +{ + public: + typedef T_shape shape_type; + typedef T_structure_id structure_id_type; + typedef DomainID domain_id_type; + + public: + Shell(){} + ~Shell(){} + + Shell(const shape_type& shape, const structure_id_type& sid) + : structure_id_(sid), shape_(shape) + {} + + Real3 const& position() const {return shape_.position();} + Real3 & position() {return shape_.position();} + + Real size() const {return shape_.size();} + Real& size() {return shape_.size();} + + domain_id_type & domain_id() {return domain_id_;} + domain_id_type const& domain_id() const {return domain_id_;} + + structure_id_type & structure_id() {return structure_id_;} + structure_id_type const& structure_id() const {return structure_id_;} + shape_type & shape() {return shape_;} + shape_type const& shape() const {return shape_;} + + std::pair get_surface_position() const + { + return std::make_pair(shape_.position(), structure_id_); + } + + private: + + domain_id_type domain_id_; + structure_id_type structure_id_; + shape_type shape_; +}; + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, + const Shell& sh) +{ + os << ""Shell(pos="" << sh.position() << "", size="" << sh.size() + << "", strid = "" << sh.structure_id() << "", domID = "" << sh.domain_id() + << "", shape="" << sh.shape() << "")""; + return os; +} + +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_SHELL */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/ShellVisitorApplier.hpp",".hpp","2614","91","#ifndef ECELL4_SGFRD_SHELL_VISITOR_APPLIER +#define ECELL4_SGFRD_SHELL_VISITOR_APPLIER +#include ""ShellContainer.hpp"" +#include ""Single.hpp"" +#include ""Pair.hpp"" +#include ""Multi.hpp"" +#include ""Birth.hpp"" + +namespace ecell4 +{ +namespace sgfrd +{ + +template +struct shell_visitor_applier +{ + T_shell_container& container_; + + shell_visitor_applier(T_shell_container& con) : container_(con){} + + template + typename Functor::result_type + operator()(Functor& f, const Single& dom) + { + return boost::apply_visitor(f, container_.get_shell(dom.shell_id())); + } + + template + typename Functor::result_type + operator()(Functor& f, const Pair& dom) + { + return boost::apply_visitor(f, container_.get_shell(dom.shell_id())); + } + + template + typename boost::enable_if< + boost::is_same, void>::type + operator()(Functor& f, const Multi& dom) + { + std::vector const& sids = dom.shell_ids(); + for(std::vector::const_iterator i(sids.begin()), e(sids.end()); + i != e; ++i) + { + boost::apply_visitor(f, container_.get_shell(*i)); + } + return; + } + + template + typename boost::enable_if< + boost::is_same, bool>::type + operator()(Functor& f, const Multi& dom) + { + std::vector const& sids = dom.shell_ids(); + for(std::vector::const_iterator i(sids.begin()), e(sids.end()); + i != e; ++i) + { + if(Functor::eval_manner::is_resolved( + boost::apply_visitor(f, container_.get_shell(*i)))) + { + return Functor::eval_manner::value; + } + } + return !Functor::eval_manner::value; + } + + template + typename boost::enable_if< + boost::is_same, void>::type + operator()(Functor&, const Birth&) + { + // Birth domain does not have any shell. do nothing. + return ; + } + + template + typename boost::disable_if< + boost::is_same, void>::type + operator()(Functor&, const Birth&) + { + // Birth domain does not have any shell. do nothing. + // if the return value is not void, return a default value. + return typename Functor::result_type(); + } + +}; + +} // sgfrd +} // ecell4 +#endif // ECELL4_SGFRD_SHELL_VISITOR_APPLIER +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/BDPropagator.hpp",".hpp","27397","774","#ifndef ECELL4_SGFRD_BD_PROPAGATOR +#define ECELL4_SGFRD_BD_PROPAGATOR +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +namespace sgfrd +{ + +/* @brief execute BD algorithm for Multi shell. * + * @tparam containerT is expected to be a World or its wrapper class */ +template +class BDPropagator +{ + // XXX clear_volume just determines the positions of potentially-overlapping + // particles. + +public: + typedef containerT container_type; + typedef volume_clearerT volume_clearer_type; + typedef ecell4::Polygon polygon_type; + + typedef ecell4::Model model_type; + typedef ecell4::Species species_type; + typedef typename container_type::particle_container_type queue_type; + + // reaction stuff + typedef ecell4::ReactionRule reaction_rule_type; + typedef ecell4::sgfrd::ReactionInfo reaction_info_type; + typedef std::pair reaction_log_type; + typedef std::vector reaction_archive_type; + +public: + + BDPropagator(const model_type& model, container_type& container, + const polygon_type& p, RandomNumberGenerator& rng, + const Real dt, const Real rl, + reaction_archive_type& last_reactions, + volume_clearer_type vc) + : max_retry_count_(1), dt_(dt), reaction_length_(rl), rejected_move_count_(0), + container_(container), model_(model), polygon_(p), rng_(rng), + last_reactions_(last_reactions), vc_(vc), queue_(container.list_particles()) + { + shuffle(rng_, queue_); + } + + bool operator()() + { + SGFRD_SCOPE(ns, BDPropagator, this->vc_.access_tracer()) + if(queue_.empty()) + { + return false; + } + + // make copy of the next particle + ParticleID pid; Particle p; + std::tie(pid, p) = queue_.back(); queue_.pop_back(); + FaceID fid = this->container_.get_face_id(pid); + + // to restore the position, copy previous state. + const Real3 prev_pos(p.position()); + const FaceID prev_fid(fid); + + if(this->attempt_reaction(pid, p, fid)) + { + return true; + } + if(p.D() == 0.0) + { + return true; + } + + // no 1st order reaction occured & particle is movable. + auto position = std::make_pair(p.position(), fid); + auto displacement = this->draw_displacement(p, fid); + this->propagate(position, displacement); + + SGFRD_TRACE(this->vc_.access_tracer().write( + ""particle %1% propagated"", pid)); + + // check escapement and clear volume if needed + { + // update local copy of particle + std::tie(p.position(), fid) = position; + if(!clear_volume(p, fid, pid)) + { + // rejected. restore position. previous position does not cause + // overlap because position and species are kept intact. + ++(this->rejected_move_count_); + p.position() = prev_pos; + fid = prev_fid; + } + } + + // retrieve possible reactants (within r1+r2+reaction_length) + auto overlapped = this->list_reaction_overlap(pid, p, fid); + + // check core-overlap + std::pair pp; Real d; + bool core_overlapped = false; + for(const auto& ppd : overlapped) + { + std::tie(pp, d) = ppd; + if(d < p.radius() + pp.second.radius()) + { + // core overlap! + // restore position and re-collect overlapped particles + p.position() = prev_pos; + fid = prev_fid; + core_overlapped = true; + break; + } + } + + if(core_overlapped) + { + overlapped = this->list_reaction_overlap(pid, p, fid); + } + else // if there is no core-overlapping, update the particle anyway + { + this->container_.update_particle(pid, p, fid); + } + + if(overlapped.empty()) + { + // no reaction-partner exists. overlaps are already cleared. update. + return true; + } + + // attempt 2nd order reaction... + const bool react = this->attempt_reaction( + pid, p, fid, overlapped.begin(), overlapped.end()); + if(!react) + { + ++(this->rejected_move_count_); + } + return true; + } + + Real dt() const throw() {return dt_;} + RandomNumberGenerator& rng() throw() {return rng_;} + volume_clearer_type const& vc() const throw() {return vc_;} + std::size_t rejected_moves() const throw() {return this->rejected_move_count_;} + + protected: + + bool attempt_reaction(const ParticleID& pid, const Particle& p, + const FaceID& fid) + { + SGFRD_SCOPE(ns, BD_attempt_single_reaction, this->vc_.access_tracer()) + + const auto& rules = this->model_.query_reaction_rules(p.species()); + SGFRD_TRACE(this->vc_.access_tracer().write( + ""%1% rules found for particle %2%"", rules.size(), pid)) + if(rules.empty()) + { + return false; + } + + const Real rnd(this->rng_.uniform(0., 1.)); + SGFRD_TRACE(this->vc_.access_tracer().write(""drawn probability = %1%"", rnd)) + Real prob = 0.; + for(const auto& rule : rules) + { + SGFRD_TRACE(this->vc_.access_tracer().write(""k * dt = %1%"", + rule.k() * dt_)) + if((prob += rule.k() * dt_) <= rnd) + { + continue; + } + if(prob >= 1.0) + { + std::cerr << ""reaction prob exceeds 1"" << std::endl; + } + + switch(rule.products().size()) + { + case 0: + { + SGFRD_TRACE(this->vc_.access_tracer().write( + ""1->0 reaction occured."")) + remove_particle(pid); + last_reactions_.push_back(std::make_pair( + rule, init_reaction_info(pid, p))); + return true; + } + case 1: + { + return attempt_reaction_1_to_1(pid, p, fid, std::make_pair( + rule, init_reaction_info(pid, p))); + } + case 2: + { + return attempt_reaction_1_to_2(pid, p, fid, std::make_pair( + rule, init_reaction_info(pid, p))); + } + default: throw NotImplemented(""BDPropagator: "" + ""more than two products from one reactant are not allowed""); + } + } + return false; + } + + template + bool attempt_reaction( + const ParticleID& pid1, const Particle& p1, const FaceID& f1, + const Iterator first, const Iterator last) + { + // Iterator::value_type == pair, Real>; + static_assert(std::is_same< + typename std::iterator_traits::value_type, + std::pair, Real> >::value, """"); + + SGFRD_SCOPE(ns, BD_attempt_pair_reaction, this->vc_.access_tracer()) + + const Real rnd(rng_.uniform(0., 1.)); + Real acc_prob = 0.; + + for(Iterator iter(first); iter != last; ++iter) + { + const ParticleID& pid2 = iter->first.first; + const Particle& p2 = iter->first.second; + + const auto& rules = + this->model_.query_reaction_rules(p1.species(), p2.species()); + if(rules.empty()) + { + // no reaction can occur because there is no rule. + continue; + } + + const Real k_tot = this->calc_k_total(rules); + acc_prob += k_tot * calc_acceptance_coef(p1, p2); + + if(acc_prob <= rnd) + { + continue; + } + else if(1.0 < acc_prob) + { + std::cerr << ""WARNING: reaction probability exceeds 1\n""; + } + + const auto& rule = this->determine_reaction_rule_from(rules, k_tot); + switch(rule.products().size()) + { + case 0: // 2->0 reaction + { + SGFRD_TRACE(this->vc_.access_tracer().write(""particle "" + ""%1% and %2% degradated"", pid1, pid2)); + this->remove_particle(pid1); + this->remove_particle(pid2); + this->last_reactions_.push_back(std::make_pair(rule, + init_reaction_info(pid1, p1, pid2, p2))); + return true; + } + case 1: + { + const FaceID& f2 = this->container_.get_face_id(pid2); + const bool reacted = this->attempt_reaction_2_to_1( + pid1, p1, f1, pid2, p2, f2, std::make_pair(rule, + init_reaction_info(pid1, p1, pid2, p2))); + if(reacted) + { + SGFRD_TRACE(this->vc_.access_tracer().write(""particle "" + ""%1% and %2% bound"", pid1, pid2)); + return true; + } + else + { + return false; + } + } + default: + { + throw NotSupported(""BDPropagator: 2 -> N (N>1) "" + ""reaction is not allowed""); + } + } + } + return false; + } + + /*! @brief A -> B case. + * particle does not move. but its radius may change. if overlap occur after + * reaction, the reaction will be rejected. if accepted, this function does + * both update and record reaction. */ + bool attempt_reaction_1_to_1( + const ParticleID& pid, const Particle& p, const FaceID& fid, + reaction_log_type rlog) + { + SGFRD_SCOPE(ns, BD_attempt_1to1_reaction, this->vc_.access_tracer()) + const auto species_new = rlog.first.products().front(); + const auto molinfo = container_.get_molecule_info(species_new); + const Real radius_new = molinfo.radius; + const Real D_new = molinfo.D; + + if(is_overlapping(std::make_pair(p.position(), fid), radius_new, pid)) + { + SGFRD_TRACE(this->vc_.access_tracer().write( + ""1->1 reaction rejected because of the overlapping"")) + return false; + } + + Particle particle_new(species_new, p.position(), radius_new, D_new); + + if(!clear_volume(particle_new, fid, pid)) + { + SGFRD_TRACE(this->vc_.access_tracer().write( + ""1->1 reaction rejected because of the overlapping(vc)"")) + return false; + } + + // check after tightening potentially-overlapping domains + if(is_overlapping(std::make_pair(p.position(), fid), radius_new, pid)) + { + return false; + } + + SGFRD_TRACE(this->vc_.access_tracer().write(""1->1 reaction occured"")) + this->container_.update_particle(pid, particle_new, fid); + rlog.second.add_product(std::make_pair(pid, particle_new)); + last_reactions_.push_back(rlog); + return true; + } + + /*! @brief A -> B + C case. + * after reaction, the products will try to move. */ + bool attempt_reaction_1_to_2( + const ParticleID& pid, const Particle& p, const FaceID& fid, + reaction_log_type rlog) + { + SGFRD_SCOPE(ns, BD_attempt_1to2_reaction, this->vc_.access_tracer()) + + const auto sp1 = rlog.first.products().at(0); + const auto sp2 = rlog.first.products().at(1); + const auto molinfo1 = container_.get_molecule_info(sp1); + const auto molinfo2 = container_.get_molecule_info(sp2); + + const Real D1 = molinfo1.D; + const Real D2 = molinfo2.D; + const Real r1 = molinfo1.radius; + const Real r2 = molinfo2.radius; + const Real D12 = D1 + D2; + const Real r12 = r1 + r2; + + if(D1 == 0. && D2 == 0) + { + throw NotSupported(""BDPropagator::1->2: "" + ""reaction between immobile particles""); + } + + const Real3 n = polygon_.triangle_at(fid).normal(); + + std::array, 2> newpfs; + newpfs[0] = std::make_pair(p.position(), fid); + newpfs[1] = std::make_pair(p.position(), fid); + + const Real separation_factor = r12 * 1e-7; + std::size_t separation_count = 10u; + while(separation_count != 0) + { + --separation_count; + SGFRD_TRACE(this->vc_.access_tracer().write( + ""separation count = %1%"", separation_count)); + + const Real3 ipv(draw_ipv(r12 + separation_factor, D12, n)); + Real3 disp1(ipv * (D1 / D12)), disp2(ipv * (-D2 / D12)); + + // put two particles next to each other + this->propagate(newpfs[0], disp1); + this->propagate(newpfs[1], disp2); + + const Real dist = ecell4::polygon::distance(this->polygon_, + newpfs[0], newpfs[1]); + if(dist <= r12) // check the new positions + { + newpfs[0] = std::make_pair(p.position(), fid); //rollback + newpfs[1] = std::make_pair(p.position(), fid); + if(separation_count == 0) + { + return false; + } + else + { + continue; + } + } + + if(is_overlapping(newpfs[0], r1, pid) || + is_overlapping(newpfs[1], r2, pid)) + { + SGFRD_TRACE(this->vc_.access_tracer().write( + ""1->2 reaction rejected because of no space"")) + return false; // no space + } + } + + std::array particles_new; + particles_new[0] = Particle(sp1, newpfs[0].first, r1, D1); + particles_new[1] = Particle(sp2, newpfs[1].first, r2, D2); + + if(!clear_volume(particles_new[0], newpfs[0].second, pid)) + { + SGFRD_TRACE(this->vc_.access_tracer().write( + ""1->2 reaction rejected because clear_volume failed (no space)"")) + return false; + } + if(!clear_volume(particles_new[1], newpfs[1].second, pid)) + { + SGFRD_TRACE(this->vc_.access_tracer().write( + ""1->2 reaction rejected because clear_volume failed (no space)"")) + return false; + } + + // check after tightening potentially-overlapping domains + if(is_overlapping(newpfs[0], r1, pid) || + is_overlapping(newpfs[1], r2, pid)) + { + return false; + } + + // this updates the old particle -> new particle + const bool update_result = this->container_.update_particle( + pid, particles_new[0], newpfs[0].second); + // this adds new particle + auto pp2 = this->container_.new_particle(particles_new[1], newpfs[1].second); + const ParticleID pid2(pp2.first.first); + + assert(!update_result); // no particle generation occured while updation + if(!pp2.second) // new particle should be inserted + { + std::cout << ""BDPropagator::attempt_reaction_1_to_2: "" + << ""attempting particle "" << pid << "" at "" + << p.position() << "" into species "" << sp1 << ""+"" << sp2 + << "" locating "" << particles_new[0] << "" and "" + << particles_new[1] << std::endl; + } + assert(pp2.second); + + SGFRD_TRACE(this->vc_.access_tracer().write(""1->2 reaction occured"")) + + //----------------------------- trial move ----------------------------- + + Integer num_move_particle = rng_.uniform_int(1, 2); + bool move_first_particle = (rng_.uniform_int(0, 1) == 0); + + while(num_move_particle != 0) + { + const ParticleID pid_to_move = (move_first_particle) ? pid : pid2; + const FaceID fid_to_move = + this->container_.get_face_id(pid_to_move); + Particle p_to_move = + this->container_.get_particle(pid_to_move).second; + + std::pair position = std::make_pair( + p_to_move.position(), fid_to_move); + Real3 displacement = draw_displacement(p_to_move, fid_to_move); + this->propagate(position, displacement); + + if(!is_overlapping(position, p_to_move.radius(), pid_to_move)) + { + const Real3 backup = p_to_move.position(); + p_to_move.position() = position.first; + if(clear_volume(p_to_move, position.second, pid_to_move)) + { + this->container_.update_particle( + pid_to_move, p_to_move, position.second); + } + else + { + p_to_move.position() = backup; + } + } + + --num_move_particle; + move_first_particle = !move_first_particle; + } + + rlog.second.add_product( + std::make_pair(pid, this->container_.get_particle(pid).second)); + rlog.second.add_product( + std::make_pair(pid2, this->container_.get_particle(pid).second)); + last_reactions_.push_back(rlog); + + return true; + } + + bool attempt_reaction_2_to_1(// XXX consider using std::tuple + const ParticleID& pid1, const Particle& p1, const FaceID& fid1, + const ParticleID& pid2, const Particle& p2, const FaceID& fid2, + reaction_log_type rlog) + { + const species_type sp_new(rlog.first.products().front()); + const auto molinfo = this->container_.get_molecule_info(sp_new); + const Real radius_new = molinfo.radius; + const Real D_new = molinfo.D; + + const Real3 pos1(p1.position()), pos2(p2.position()); + const Real D1(p1.D()), D2(p2.D()); + const Real D12(D1 + D2); + + // this calculates the center position weighted by Diffusion coef. + + std::pair pf1; + if(D1 == 0.0) + { + pf1 = std::make_pair(pos1, fid1); + } + else if(D2 == 0.0) + { + pf1 = std::make_pair(pos2, fid2); + } + else + { + Real3 dp = ecell4::polygon::direction(this->polygon_, + std::make_pair(pos1, fid1), std::make_pair(pos2, fid2)) * (D1 / D12); + pf1 = std::make_pair(pos1, fid1); + this->propagate(pf1, dp); + } + + const Particle particle_new(sp_new, pf1.first, radius_new, D_new); + if(!clear_volume(particle_new, pf1.second, pid1, pid2)) + { + // the new particle locates at the CoM of the two particles + // collides with others, return without reaction. + return false; + } + + // check after tightening potentially-overlapping domains + if(is_overlapping(pf1, radius_new, pid1, pid2)) + { + return false; + } + + remove_particle(pid2); + remove_particle(pid1); + const std::pair, bool> pp_new = + this->container_.new_particle(particle_new, pf1.second); + + if(!pp_new.second) + { + // this should not fail. because we already cleared the volume. + std::cout << ""pid1 = "" << pid1 << std::endl; + std::cout << ""pid2 = "" << pid2 << std::endl; + assert(pp_new.second); + } + + rlog.second.add_product(pp_new.first); + last_reactions_.push_back(rlog); + + return true; + } + + void remove_particle(const ParticleID& pid) + { + container_.remove_particle(pid); + const typename std::vector >::iterator i( + std::find_if(queue_.begin(), queue_.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(pid))); + if(i != queue_.end()) + { + queue_.erase(i); + } + return; + } + + void remove_particle(const ParticleID& pid, const FaceID& fid) + { + container_.remove_particle(pid, fid); + const typename std::vector >::iterator i( + std::find_if(queue_.begin(), queue_.end(), + ecell4::utils::pair_first_element_unary_predicator< + ParticleID, Particle>(pid))); + if(i != queue_.end()) + { + queue_.erase(i); + } + return; + } + + bool is_overlapping( + const std::pair& pos, const Real& rad, + const ParticleID& pid) const + { + return !(this->container_.check_no_overlap(pos, rad, pid)); + } + bool is_overlapping( + const std::pair& pos, const Real& rad, + const ParticleID& pid1, const ParticleID& pid2) const + { + return !(this->container_.check_no_overlap(pos, rad, pid1, pid2)); + } + + std::vector, Real> > + list_reaction_overlap(const ParticleID& pid, const Particle& p, + const FaceID& fid) const + { + return this->container_.list_particles_within_radius( + std::make_pair(p.position(), fid), p.radius() + reaction_length_, pid); + } + + void propagate(std::pair& pos, Real3& disp) const + { + pos = ecell4::polygon::travel(this->polygon_, pos, disp); + return ; + } + + /*! clear the region that particle will occupy. returns if succeed. + * this may burst some domains that overlap with particle. */ + bool clear_volume(const Particle& p, const FaceID& fid) + { + return vc_(p, fid); + } + + bool clear_volume(const Particle& p, const FaceID& fid, + const ParticleID& ignore) + { + return vc_(p, fid, ignore); + } + + bool clear_volume(const Particle& p, const FaceID& fid, + const ParticleID& ignore1, const ParticleID& ignore2) + { + return vc_(p, fid, ignore1, ignore2); + } + + Real3 random_circular_uniform(const Real& r) + { + const Real theta = this->rng_.uniform(0., 2 * M_PI); + return Real3(r * std::cos(theta), r * std::sin(theta), 0.); + } + + Real3 random_circular_uniform(const Real r, const Real3& normal) + { + const Real3 rnd = random_circular_uniform(r); + const Real tilt = calc_angle(Real3(0, 0, 1), normal); + + if (std::abs(tilt) < 1e-10) {return rnd;} + else if(std::abs(tilt - M_PI) < 1e-10) {return rnd * (-1.0);} + else if(std::abs(tilt + M_PI) < 1e-10) {return rnd * (-1.0);} + + const Real3 axis = cross_product(Real3(0., 0., 1.), normal); + return rotate(tilt, axis * (1. / length(axis)), rnd); + } + + Real3 draw_displacement(const Particle& p, const FaceID& fid) + { + const Real r = rng_.gaussian(std::sqrt(4 * p.D() * dt_)); + return random_circular_uniform(r, polygon_.triangle_at(fid).normal()); + } + + Real3 draw_ipv(const Real r, const Real D, const Real3& normal) + { + const Real rl = r + this->reaction_length_; + const Real r_sq = r * r; + const Real rd = rl * rl - r_sq; + const Real ipvl = std::sqrt(r_sq + this->rng_.uniform(0., 1.) * rd); + return random_circular_uniform(ipvl, normal); + } + + Real calc_reaction_area(const Real radius_sum) const + { + const Real rad_react(radius_sum + this->reaction_length_); + return M_PI * (rad_react * rad_react - radius_sum * radius_sum); + } + + Real calc_acceptance_coef(const Particle& p1, const Particle& p2) const + { + const Real reaction_area = calc_reaction_area(p1.radius() + p2.radius()); + if((p1.D() == 0) || (p2.D() == 0)) + { + // immovable particles immediately return after attempting 1st order + // reaction. + // to attempt 2nd order reaction with them, we need to double the + // acceptance coefficient. + return dt_ / reaction_area; + } + else + { + // movable particles checks 2nd order reaction. If the both reactants + // are movable, both particle attempts reaction. So here it halves + // the acceptance coefficient to avoid double-counting. + return 0.5 * dt_ / reaction_area; + } + } + + Real calc_k_total(const std::vector& rules) const noexcept + { + Real k_tot(0.0); + if(rules.empty()) + { + return k_tot; + } + if(rules.size() == 1) + { + return rules.front().k(); + } + for(const auto& rule : rules) + { + k_tot += rule.k(); + } + return k_tot; + } + + reaction_rule_type const& + determine_reaction_rule_from(const std::vector& rules, + const Real k_tot) const noexcept + { + assert(!rules.empty()); + if(rules.size() == 1) + { + return rules.front(); + } + const Real rnd(rng_.uniform(0.0, 1.0) * k_tot); + Real k_cumm(0.0); + for(const auto& rule : rules) + { + k_cumm += rule.k(); + if(rnd < k_cumm) + { + return rule; + } + } + return rules.back(); + } + + reaction_info_type init_reaction_info(const ParticleID& pid, const Particle& p) + { + return reaction_info_type(container_.t(), + reaction_info_type::container_type(1, std::make_pair(pid, p)), + reaction_info_type::container_type()); + } + + reaction_info_type + init_reaction_info(const ParticleID& pid1, const Particle& p1, + const ParticleID& pid2, const Particle& p2) + { + typename reaction_info_type::container_type reactants(2); + typename reaction_info_type::container_type products; + reactants[0] = std::make_pair(pid1, p1); + reactants[1] = std::make_pair(pid2, p2); + return reaction_info_type(container_.t(), reactants, products); + } + + +protected: + + Integer max_retry_count_; + Real dt_; + Real reaction_length_; + std::size_t rejected_move_count_; + container_type& container_; + model_type const& model_; + polygon_type const& polygon_; + RandomNumberGenerator& rng_; + reaction_archive_type& last_reactions_; + volume_clearer_type vc_; + queue_type queue_; +}; + +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_BD_PROPAGATOR */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/Single.hpp",".hpp","1932","71","#ifndef ECELL4_SGFRD_SINGLE_DOMAIN +#define ECELL4_SGFRD_SINGLE_DOMAIN +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class Single +{ + public: + + enum EventKind + { + ESCAPE, + REACTION, + UNKNOWN, + }; + + typedef ShellID shell_id_type; + typedef Particle particle_type; + typedef ParticleID particle_id_type; + typedef std::pair particle_id_pair_type; + + public: + Single(): kind_(UNKNOWN), dt_(0.), begin_time_(0.){} + Single(const EventKind kind, const Real dt, const Real begin_time, + const shell_id_type shid, const particle_id_pair_type& pidp) + : kind_(kind), dt_(dt), begin_time_(begin_time), + shell_id_(shid), particle_(pidp) + {} + ~Single(){} + + shell_id_type& shell_id() {return shell_id_;} + shell_id_type const& shell_id() const {return shell_id_;} + + Real& dt() {return dt_;} + Real dt() const {return dt_;} + Real& begin_time() {return begin_time_;} + Real begin_time() const {return begin_time_;} + + EventKind eventkind() const {return kind_;} + EventKind& eventkind() {return kind_;} + + particle_id_pair_type& particle_id_pair() {return particle_;} + particle_id_pair_type const& particle_id_pair() const {return particle_;} + + Particle& particle() {return particle_.second;} + Particle const& particle() const {return particle_.second;} + ParticleID& particle_id() {return particle_.first;} + ParticleID const& particle_id() const {return particle_.first;} + + std::size_t num_shells() const {return 1;} + std::size_t multiplicity() const {return 1;} + + private: + + EventKind kind_; + Real dt_; + Real begin_time_; + shell_id_type shell_id_; + particle_id_pair_type particle_; +}; + + +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_SINGLE_DOMAIN */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/BDSimulator.hpp",".hpp","8103","232","#ifndef ECELL4_SGFRD_BD_SIMULATOR +#define ECELL4_SGFRD_BD_SIMULATOR + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class BDSimulator : + public ecell4::SimulatorBase +{ + public: + typedef BDSimulator self_type; + + // polygon + typedef ecell4::Polygon polygon_type; + + // world & particles + typedef ecell4::SimulatorBase base_type; + typedef base_type::world_type world_type; + typedef base_type::model_type model_type; + typedef std::pair particle_id_pair_type; + + // reaction + typedef ecell4::ReactionRule reaction_rule_type; + typedef ReactionInfo reaction_info_type; + typedef std::pair reaction_log_type; + typedef std::vector reaction_archive_type; + + BDSimulator(const std::shared_ptr& world, + const std::shared_ptr& model, + Real bd_dt_factor = 1e-5, Real reaction_length = 1e-3, + const std::string& trace_fname = ""bd_trace.log"") + : base_type(world, model), dt_(bd_dt_factor/*TODO*/), + bd_dt_factor_(bd_dt_factor), reaction_length_(reaction_length), + rng_(*(world->rng())), tracer_(trace_fname) + {} + + BDSimulator(std::shared_ptr world, + Real bd_dt_factor = 1e-5, Real reaction_length = 1e-3, + const std::string& trace_fname = ""bd_trace.log"") + : base_type(world), dt_(bd_dt_factor/*TODO*/), + bd_dt_factor_(bd_dt_factor), reaction_length_(reaction_length), + rng_(*(world->rng())), tracer_(trace_fname) + {} + + void initialize() + { + assert(this->diagnosis()); + return; + } + void finalize() + { + return; + } + void finalize(const Real t) + { + SGFRD_SCOPE(us, finalize, tracer_); + + this->world_->set_t(t); + BDPropagator propagator( + *(this->model_), *(this->world_), + *(this->world_->polygon()), this->rng_, + t - this->world_->t(), this->reaction_length_, + this->last_reactions_, + volume_clearer(*(this->world_), this->tracer_)); + + while(propagator()) + { + // do nothing + } + return; + } + + void step() + { + SGFRD_SCOPE(us, step, tracer_); + + const Real next_time = this->world_->t() + this->dt_; + this->world_->set_t(next_time); + SGFRD_TRACE(tracer_.write(""now t = %1%"", this->world_->t())) + SGFRD_TRACE(tracer_.write(""dt = %1%"", this->dt_)) + + BDPropagator propagator( + *(this->model_), *(this->world_), + *(this->world_->polygon()), this->rng_, + this->dt_, this->reaction_length_, + this->last_reactions_, + volume_clearer(*(this->world_), this->tracer_)); + + SGFRD_TRACE(tracer_.write(""propagating..."")) + while(propagator()) + { + // do nothing + } + SGFRD_TRACE(tracer_.write(""...done!"")) + return; + } + bool step(const Real& upto) + { + this->step(); + return this->world_->t() < upto; + } + + Real dt() const {return dt_;} + Real reaction_length() const {return reaction_length_;} + + bool check_reaction() const {return last_reactions_.size() > 0;} + + std::vector > const& + last_reactions() const {return last_reactions_;} + + Real next_event_time() const + { + return this->world_->t() + this->dt_; + } + + struct volume_clearer + { + volume_clearer(world_type const& wld, tracer& tr) + : world_(wld), tracer_(tr) + {} + + bool operator()(const Particle& p, const FaceID& fid) const + { + return world_.check_no_overlap(std::make_pair(p.position(), fid), + p.radius()); + } + bool operator()(const Particle& p, const FaceID& fid, + const ParticleID& ignore) const + { + return world_.check_no_overlap(std::make_pair(p.position(), fid), + p.radius(), ignore); + } + bool operator()(const Particle& p, const FaceID& fid, + const ParticleID& ign1, const ParticleID& ign2) const + { + return world_.check_no_overlap(std::make_pair(p.position(), fid), + p.radius(), ign1, ign2); + } + + tracer& access_tracer() {return this->tracer_;} + + const world_type& world_; + tracer& tracer_; + }; + + bool diagnosis() + { + SGFRD_SCOPE(us, diagnosis, tracer_); + bool result = true; + auto particles = this->world_->list_particles(); + + ParticleID pid; Particle p; + for(const auto& pidp : particles) + { + std::tie(pid, p) = pidp; + const FaceID fid = this->world_->get_face_id(pid); + std::pair pos = std::make_pair(p.position(), fid); + + ParticleID _pid; Particle _p; + for(const auto& _pidp : particles) + { + std::tie(_pid, _p) = _pidp; + if(pid == _pid) {continue;} + const FaceID _fid = this->world_->get_face_id(_pid); + const Real dist = this->world_->distance(pos, + std::make_pair(_p.position(), _fid)); + if(dist < p.radius() + _p.radius()) + { + result = false; + std::cerr << ""ERROR: particle "" << pid << "" and "" << _pid + << ""overlaps!\n""; + std::cerr << "" : distance = "" << dist << "" < sum of radii = "" + << p.radius() + _p.radius() << '\n'; + std::cerr << "" : particle "" << pid << "" has radius "" + << p.radius() << "" at "" << p.position() << "" on "" + << fid << '\n'; + std::cerr << "" : particle "" << _pid << "" has radius "" + << _p.radius() << "" at "" << _p.position() << "" on "" + << _fid << '\n'; + } + } + + if(!this->world_->polygon()->is_inside_of_boundary(p.position())) + { + std::cerr << ""ERROR: particle "" << pid << "" is outside of the boundary!\n""; + std::cerr << "" : position = "" << p.position() + << "", boundary = "" << this->world_->polygon()->edge_lengths() << ""\n""; + result = false; + } + + const Triangle& tri = this->world_->polygon()->triangle_at(fid); + const Barycentric bary = ::ecell4::to_barycentric(p.position(), tri); + if(!is_inside(bary)) + { + std::cerr << ""ERROR: particle "" << pid << "" is not on the face "" << fid << ""\n""; + std::cerr << "" : position = "" << p.position() << "", face = "" << tri << ""\n""; + std::cerr << "" : barycentric = "" << bary << "", face = "" << tri << ""\n""; + result = false; + } + } + return result; + } + + private: + // from SimulatorBase + // std::shared_ptr model_; + // std::shared_ptr world_; + // Integer num_steps_; + + Real dt_; + Real bd_dt_factor_; + Real reaction_length_; + ecell4::RandomNumberGenerator& rng_; + std::vector > last_reactions_; + mutable tracer tracer_; +}; + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_BD_SIMULATOR +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/Pair.hpp",".hpp","4312","140","#ifndef ECELL4_SGFRD_PAIR_DOMAIN +#define ECELL4_SGFRD_PAIR_DOMAIN +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class Pair +{ + public: + + enum EventKind + { + SINGLE_REACTION_1, + SINGLE_REACTION_2, + COM_ESCAPE, + IV_ESCAPE, + IV_REACTION, + IV_UNDETERMINED, + UNDETERMINED + }; + + typedef ShellID shell_id_type; + typedef Particle particle_type; + typedef ParticleID particle_id_type; + typedef std::pair particle_id_pair; + typedef std::array particle_array_type; + + static Real calc_D_ipv(const Real D1, const Real D2) throw() + { + return D1 + D2; + } + + static Real calc_D_com(const Real D1, const Real D2) throw() + { + return D1 * D2 / (D1 + D2); + } + + static Real calc_R_ipv(const Real r_shell, + const Particle& p1, const Particle& p2) throw() + { + const Real r_sep = r_shell * (1.0-1e-7); + const Real Dipv = calc_D_ipv(p1.D(), p2.D()); + const Real Dcom = calc_D_com(p1.D(), p2.D()); + return r_sep * Dipv / (Dipv + Dcom); + } + static Real calc_R_com(const Real r_shell, + const Particle& p1, const Particle& p2) throw() + { + const Real r_sep = r_shell * (1.0-1e-7); + const Real Dipv = calc_D_ipv(p1.D(), p2.D()); + const Real Dcom = calc_D_com(p1.D(), p2.D()); + return r_sep * Dcom / (Dipv + Dcom); + } + + public: + + Pair(): kind_(UNDETERMINED), dt_(0.), begin_time_(0.){} + ~Pair(){} + + Pair(const EventKind kind, const Real dt, const Real begin_time, + const shell_id_type& sh, const Real shell_rad, + const particle_id_pair& p0, const particle_id_pair& p1, + const Real r0, const Real3& ipv, const Real kf) + : kind_(kind), dt_(dt), begin_time_(begin_time), + r0_(r0), kf_(kf), ipv_(ipv), shell_id_(sh) + { + particles_[0] = p0; + particles_[1] = p1; + this->r_ipv_ = Pair::calc_R_ipv(shell_rad, p0.second, p1.second); + this->r_com_ = Pair::calc_R_com(shell_rad, p0.second, p1.second); + this->D_ipv_ = Pair::calc_D_ipv(p0.second.D(), p1.second.D()); + this->D_com_ = Pair::calc_D_com(p0.second.D(), p1.second.D()); + assert(this->r_ipv_ + this->r_com_ < shell_rad); + } + + EventKind eventkind() const {return kind_;} + EventKind& eventkind() {return kind_;} + + shell_id_type& shell_id() throw() {return shell_id_;} + shell_id_type const& shell_id() const throw() {return shell_id_;} + + Real& dt() throw() {return dt_;} + Real dt() const throw() {return dt_;} + Real& begin_time() throw() {return begin_time_;} + Real begin_time() const throw() {return begin_time_;} + + Real r0() const throw() {return this->r0_;} + Real kf() const throw() {return this->kf_;} + Real sigma() const throw() {return this->particles_[0].second.radius() + + this->particles_[1].second.radius();} + Real R_ipv() const throw() {return this->r_ipv_;} + Real R_com() const throw() {return this->r_com_;} + Real D_ipv() const throw() {return this->D_ipv_;} + Real D_com() const throw() {return this->D_com_;} + + Real3 const& ipv() const throw() {return this->ipv_;} + + particle_id_pair& operator[](std::size_t i) throw() + {return particles_[i];} + particle_id_pair const& operator[](std::size_t i) const throw() + {return particles_[i];} + + ParticleID const& particle_id_at(const std::size_t i) const throw() + { + return particles_.at(i).first; + } + + Particle const& particle_at(const std::size_t i) const throw() + { + return particles_.at(i).second; + } + + std::size_t num_shells() const throw() {return 1;} + std::size_t multiplicity() const throw() {return 2;} + + private: + + EventKind kind_; + Real dt_; + Real begin_time_; + Real r0_; + Real kf_; + Real r_ipv_; + Real r_com_; + Real D_ipv_; + Real D_com_; + Real3 ipv_; + shell_id_type shell_id_; + particle_array_type particles_; +}; + +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_PAIR_DOMAIN */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/expected.hpp",".hpp","4953","188","#ifndef ECELL4_SGFRD_EXPECTED +#define ECELL4_SGFRD_EXPECTED +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +template +struct success +{ + typedef T value_type; + + success() = default; + ~success() = default; + success(const success&) = default; + success(success&&) = default; + success& operator=(const success&) = default; + success& operator=(success&&) = default; + + explicit success(const value_type& v) + noexcept(noexcept(std::is_nothrow_copy_constructible::value)) + : value(v) + {} + explicit success(value_type&& v) + noexcept(noexcept(std::is_nothrow_move_constructible::value)) + : value(std::move(v)) + {} + + value_type value; +}; + +template<> +struct success +{ + typedef void value_type; + + success() = default; + ~success() = default; + success(const success&) = default; + success(success&&) = default; + success& operator=(const success&) = default; + success& operator=(success&&) = default; +}; + +template +struct failure +{ + typedef T value_type; + + failure() = default; + ~failure() = default; + failure(const failure&) = default; + failure(failure&&) = default; + failure& operator=(const failure&) = default; + failure& operator=(failure&&) = default; + + explicit failure(const value_type& v) + noexcept(noexcept(std::is_nothrow_copy_constructible::value)) + : value(v) + {} + explicit failure(value_type&& v) + noexcept(noexcept(std::is_nothrow_move_constructible::value)) + : value(std::move(v)) + {} + + value_type value; +}; + +template<> +struct failure +{ + typedef void value_type; + + failure() = default; + ~failure() = default; + failure(const failure&) = default; + failure(failure&&) = default; + failure& operator=(const failure&) = default; + failure& operator=(failure&&) = default; +}; + +template +inline +success::type>::type> +ok(T&& v) +{ + return success< + typename std::remove_cv::type>::type + >(std::forward(v)); +} +inline success ok() +{ + return success(); +} + +template +inline +failure::type>::type> +err(T&& v) +{ + return failure< + typename std::remove_cv::type>::type + >(std::forward(v)); +} +inline failure err() +{ + return failure(); +} + +template +class expected +{ + public: + typedef T value_type; + typedef E error_type; + typedef success success_type; + typedef failure failure_type; + + public: + + expected() = delete; // expected should be initialized + ~expected() = default; + expected(const expected& v) = default; + expected(expected&& v) = default; + expected& operator=(const expected& v) = default; + expected& operator=(expected&& v) = default; + + expected(const success_type& s) : result_(s) {} + expected(const failure_type& f) : result_(f) {} + expected(success_type&& s) : result_(std::move(s)) {} + expected(failure_type&& f) : result_(std::move(f)) {} + expected& operator=(const success_type& v){result_ = v; return *this;} + expected& operator=(const failure_type& e){result_ = e; return *this;} + expected& operator=(success_type&& v){result_ = std::move(v); return *this;} + expected& operator=(failure_type&& e){result_ = std::move(e); return *this;} + + const value_type& unwrap() const + { + if(!this->is_ok()) + { + throw std::runtime_error(""ecell4::expected::unwrap: not ok""); + } + return boost::get(result_).value; + } + + const error_type& unwrap_error() const + { + if(!this->is_err()) + { + throw std::runtime_error( + ""ecell4::expected::unwrap_error: not an error""); + } + return boost::get(this->result_).value; + } + + bool is_ok() const noexcept {return this->result_.which() == 0;} + bool is_err() const noexcept {return this->result_.which() == 1;} + operator bool() const noexcept {return this->is_ok();} + + boost::optional ok() const noexcept + { + if(this->is_ok()) + { + return boost::get(this->result_).value; + } + return boost::none; + } + boost::optional err() const noexcept + { + if(this->is_err()) + { + return boost::get(this->result_).value; + } + return boost::none; + } + + private: + + boost::variant result_; +}; + +} // ecell4 +#endif// ECELL4_SGFRD_EXPECTED +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/distance_calculator.hpp",".hpp","1796","70","#ifndef ECELL4_SGFRD_DISTANCE_CALCULATOR +#define ECELL4_SGFRD_DISTANCE_CALCULATOR +#include +#include +#include +#include +#include ""distance.hpp"" +#include ""Shell.hpp"" + +namespace ecell4 +{ +namespace sgfrd +{ + +struct distance_calculator : public boost::static_visitor +{ + distance_calculator(const Real3& pos): pos_(pos){} + + template + Real operator()(const Shell& sh) const + { + return ecell4::sgfrd::distance(pos_, sh.shape()) - sh.size(); + } + + private: + Real3 pos_; +}; + +template +struct distance_calculator_on_surface : public boost::static_visitor +{ +public: + typedef strID structure_id_type; + typedef ecell4::Polygon polygon_type; + +private: + + template + struct is_2d_shell : std::integral_constant::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) + > + {}; + +public: + + distance_calculator_on_surface( + const std::pair& pos, + const polygon_type& poly) + : poly_(poly), pos_(pos) + {} + + template + typename std::enable_if::value, Real>::type + operator()(const Shell& sh) const + { + return ecell4::polygon::distance(poly_, pos_, sh.get_surface_position()) - + sh.size(); + } + +private: + + polygon_type const& poly_; + std::pair pos_; +}; + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_DISTANCE_CALCULATOR +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/Multi.hpp",".hpp","6660","211","#ifndef ECELL4_SGFRD_MULTI_DOMAIN +#define ECELL4_SGFRD_MULTI_DOMAIN +#include +#include +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class SGFRDSimulator; + +class Multi +{ + public: + + enum EventKind + { + NONE, + ESCAPE, + REACTION, + }; + + typedef std::pair particle_id_pair_type; + typedef std::vector particles_type; + typedef std::vector shell_ids_type; + + typedef SGFRDWorld world_type; + typedef world_type::polygon_type polygon_type; + typedef world_type::model_type model_type; + typedef SGFRDSimulator simulator_type; + typedef MultiContainer container_type; + + typedef ecell4::ReactionRule reaction_rule_type; + typedef ecell4::sgfrd::ReactionInfo reaction_info_type; + typedef std::pair reaction_log_type; + typedef std::vector reaction_archive_type; + + public: + + Multi(simulator_type& sim, world_type& world, + Real dt_factor = 0.01, Real rl_factor = 0.1 /* [0.05 ~ 0.1] */) + : kind_(NONE), dt_(-1.0), begin_time_(0.), reaction_length_(-1.0), + dt_factor_(dt_factor), reaction_length_factor_(rl_factor), + simulator_(sim), world_(world), model_(*world.lock_model()), + container_(world) + {} + + Multi(simulator_type& sim, world_type& world, Real begin_t, + Real dt_factor = 0.01, Real rl_factor = 0.1 /* [0.05 ~ 0.1] */) + : kind_(NONE), dt_(-1.0), begin_time_(begin_t), reaction_length_(-1.0), + dt_factor_(dt_factor), reaction_length_factor_(rl_factor), + simulator_(sim), world_(world), model_(*world.lock_model()), + container_(world) + {} + ~Multi(){} + + template + void step(vcT vc) + { + step(vc, this->dt_); + return ; + } + + template + void step(vcT vc, const Real dt) + { + assert(this->dt_ > 0.0); + assert(this->reaction_length_ > 0.0); + + this->last_reactions_.clear(); + kind_ = NONE; + + BDPropagator propagator(model_, container_, + *(world_.polygon()), *(world_.rng()), dt, reaction_length_, + last_reactions_, vc); + + while(propagator()) + { + // if reaction occurs, return immediately + // XXX is it okay? + if(!last_reactions_.empty()) + { + kind_ = REACTION; + break; + } + if(propagator.vc().escaped()) + { + kind_ = ESCAPE; + } + } + } + + EventKind& eventkind() {return kind_;} + EventKind eventkind() const {return kind_;} + + Real& dt() {return dt_;} + Real dt() const {return dt_;} + Real& begin_time() {return begin_time_;} + Real begin_time() const {return begin_time_;} + Real& reaction_length() {return reaction_length_;} + Real reaction_length() const {return reaction_length_;} + + void determine_parameters() + { + this->determine_reaction_length(); + this->determine_delta_t(); + return; + } + + void determine_reaction_length() + { + Real r_min = std::numeric_limits::max(); + for(const auto& p : this->particles()) + { + r_min = std::min(p.second.radius(), r_min); + } + reaction_length_ = this->reaction_length_factor_ * r_min; + return; + } + void determine_delta_t() + { + // it assumes this->determine_reaction_length() has already been called + assert(this->reaction_length_ > 0.0); + + // collect possible reactions and find maximum D + std::vector sps; + sps.reserve(this->particles().size()); + Real D_max = -std::numeric_limits::max(); + for(const auto& p : this->particles()) + { + D_max = std::max(p.second.D(), D_max); + if(std::find(sps.begin(), sps.end(), p.second.species()) == sps.end()) + { + sps.push_back(p.second.species()); + } + } + + Real k_max = 0.0; + if(sps.size() >= 2) + { + // TODO: make it more efficient ... ? + for(std::size_t i=0; i B"". + for(std::size_t j=i; jreaction_length_; + + const Real upper_limit_D = delta * delta / D_max; + const Real upper_limit_k = (k_max > 0.0) ? (P_max * delta / k_max) : + std::numeric_limits::infinity(); + this->dt_ = this->dt_factor_ * std::min(upper_limit_D, upper_limit_k); + return; + } + + bool add_particle(ParticleID const& pid) + { + return container_.make_entry(pid); + } + bool add_shell(ShellID const& sid) + { + if(std::find(shells_.begin(), shells_.end(), sid) != shells_.end()) + { + return false; + } + shells_.push_back(sid); + return true; + } + + shell_ids_type& shell_ids() {return shells_;} + shell_ids_type const& shell_ids() const {return shells_;} + particles_type& particles() {return container_.list_particles();} + particles_type const& particles() const {return container_.list_particles();} + + std::size_t num_shells() const {return shells_.size();} + std::size_t multiplicity() const {return container_.num_particles();} + + reaction_archive_type const& last_reactions() const {return last_reactions_;} + + private: + + EventKind kind_; + Real dt_, begin_time_, reaction_length_; + Real dt_factor_, reaction_length_factor_; + simulator_type& simulator_; + world_type& world_; + model_type& model_; + container_type container_; + shell_ids_type shells_; + reaction_archive_type last_reactions_; +}; + +} // sgfrd +} // ecell4 +#endif /* ECELL4_SGFRD_MULTI_DOMAIN */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/ReactionInfo.hpp",".hpp","3603","132","#ifndef ECELL4_SGFRD_REACTION_INFO +#define ECELL4_SGFRD_REACTION_INFO +#include +#include +#include + +namespace ecell4 +{ +namespace sgfrd +{ + +class ReactionInfo +{ +public: + + typedef std::pair particle_id_pair_type; + typedef std::vector container_type; + +public: + + ReactionInfo( + const Real t, + const container_type& reactants, + const container_type& products) + : t_(t), reactants_(reactants), products_(products) + {} + + ReactionInfo(const ReactionInfo& another) + : t_(another.t()), reactants_(another.reactants()), products_(another.products()) + {} + + Real t() const + { + return t_; + } + + const container_type& reactants() const + { + return reactants_; + } + + void add_reactant(const particle_id_pair_type& pid_pair) + { + reactants_.push_back(pid_pair); + } + + const container_type& products() const + { + return products_; + } + + void add_product(const particle_id_pair_type& pid_pair) + { + products_.push_back(pid_pair); + } + +protected: + + Real t_; + container_type reactants_, products_; +}; + +inline ReactionInfo +make_degradation_reaction_info( + const Real t, const ParticleID& pid, const Particle& p) +{ + typedef ReactionInfo::container_type container_type; + return ReactionInfo(t, container_type(1, std::make_pair(pid, p)), + container_type(0)); +} + +inline ReactionInfo +make_degradation_reaction_info(const Real t, + const ParticleID& pid1, const Particle& p1, + const ParticleID& pid2, const Particle& p2) +{ + typedef ReactionInfo::container_type container_type; + container_type cont(2); + cont[0] = std::make_pair(pid1, p1); + cont[1] = std::make_pair(pid2, p2); + return ReactionInfo(t, cont, container_type(0)); +} + +inline ReactionInfo +make_synthesis_reaction_info( + const Real t, const ParticleID& pid, const Particle& p) +{ + typedef ReactionInfo::container_type container_type; + return ReactionInfo(t, container_type(0), + container_type(1, std::make_pair(pid, p))); +} + +inline ReactionInfo +make_unimolecular_reaction_info(const Real t, + const ParticleID& pid1, const Particle& p1, + const ParticleID& pid2, const Particle& p2) +{ + typedef ReactionInfo::container_type container_type; + return ReactionInfo(t, container_type(1, std::make_pair(pid1, p1)), + container_type(1, std::make_pair(pid2, p2))); +} + +inline ReactionInfo +make_binding_reaction_info(const Real t, + const ParticleID& pid1, const Particle& p1, + const ParticleID& pid2, const Particle& p2, + const ParticleID& pid3, const Particle& p3) +{ + typedef ReactionInfo::container_type container_type; + container_type cont(2); + cont[0] = std::make_pair(pid1, p1); + cont[1] = std::make_pair(pid2, p2); + return ReactionInfo(t, cont, container_type(1, std::make_pair(pid3, p3))); +} + +inline ReactionInfo +make_unbinding_reaction_info(const Real t, + const ParticleID& pid1, const Particle& p1, + const ParticleID& pid2, const Particle& p2, + const ParticleID& pid3, const Particle& p3) +{ + typedef ReactionInfo::container_type container_type; + container_type cont(2); + cont[0] = std::make_pair(pid2, p2); + cont[1] = std::make_pair(pid3, p3); + return ReactionInfo(t, container_type(1, std::make_pair(pid1, p1)), cont); +} + +} // sgfrd +} // ecell4 +#endif// ECELL4_SGFRD_REACTION_AND_MOLECULE_INFO +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/samples/bdonly.cpp",".cpp","8812","242","#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +void snapshot_output(std::ofstream& outstr, + const std::shared_ptr& world) +{ + typedef ecell4::sgfrd::SGFRDWorld::particle_container_type container; + container const ps = world->list_particles(); + for(container::const_iterator iter = ps.begin(); iter != ps.end(); ++iter) + { + outstr << world->t() << ' ' + << iter->second.species().serial() << ' ' + << iter->second.position()[0] << ' ' + << iter->second.position()[1] << ' ' + << iter->second.position()[2] << '\n'; + } + outstr << ""\n\n"" << std::flush; + return; +} + +void species_output(std::ofstream& outstr, + const std::shared_ptr& world, + const ecell4::Species& sp1, const ecell4::Species& sp2, + const ecell4::Species& sp3) +{ + outstr << world->t() << ' ' + << world->num_molecules(sp1) << ' ' + << world->num_molecules(sp2) << ' ' + << world->num_molecules(sp3) << std::endl; + return; +} + +void reaction_output( + std::ofstream& outstr, const ecell4::sgfrd::BDSimulator& sim) +{ + typedef ecell4::sgfrd::BDSimulator::reaction_rule_type reaction_rule_type; + typedef ecell4::sgfrd::BDSimulator::reaction_info_type reaction_info_type; + typedef std::vector > + reaction_record_type; + + reaction_record_type const& rr = sim.last_reactions(); + for(reaction_record_type::const_iterator iter = rr.begin(), end_ = rr.end(); + iter != end_; ++iter) + { + outstr << ""rule: "" << iter->first.as_string() << "" : ""; + outstr << ""t = "" << iter->second.t() << "", reactant = { ""; + for(reaction_info_type::container_type::const_iterator + r_iter = iter->second.reactants().begin(), + r_end = iter->second.reactants().end(); r_iter != r_end; ++r_iter) + { + outstr << r_iter->first; + } + outstr << ""}, products = { ""; + for(reaction_info_type::container_type::const_iterator + p_iter = iter->second.products().begin(), + p_end = iter->second.products().end(); p_iter != p_end; ++p_iter) + { + outstr << p_iter->first; + } + outstr << '}' << std::endl; + } + + return; +} + + +bool key_missing( + std::map const& inp, std::string const& key) +{ + if(inp.count(key) != 1) + { + std::cerr << ""missing key "" << key << "" in input file"" << std::endl; + return true; + } + return false; +} + +int main(int argc, char **argv) +{ + typedef ecell4::sgfrd::polygon_traits polygon_traits; + typedef ecell4::Polygon polygon_type; + typedef ecell4::sgfrd::SGFRDWorld world_type; + typedef ecell4::sgfrd::BDSimulator simulator_type; + typedef polygon_type::face_id_type face_id_type; + + if(argc != 2) + { + std::cerr << ""Usage: "" << argv[0] << "" input.inp"" << std::endl; + return 1; + } + + const std::string inpname(argv[1]); + std::ifstream ifs(inpname.c_str()); + if(!ifs.good()) + { + std::cerr << ""file open error: "" << inpname << std::endl; + return 1; + } + + std::map input; + while(!ifs.eof()) + { + std::string line; + std::getline(ifs, line); + if(line.empty() || line[0] == '#') continue; + + std::istringstream iss(line); + std::string key, equal, value; + iss >> key >> equal >> value; + if(equal != ""="") + { + std::cerr << ""invalid line in input file: "" << line << std::endl; + return 1; + } + input.insert(std::make_pair(key, value)); + ifs.peek(); + } + + ecell4::STLFileReader reader; + ecell4::STLPolygonAdapter adapter; + + if(key_missing(input, ""polygon"")){return 1;} + std::shared_ptr polygon = + adapter.make_polygon(reader.read(input[""polygon""], ecell4::STLFileReader::Ascii)); + + if(key_missing(input, ""system_size"")) return 1; + const ecell4::Real L(boost::lexical_cast(input[""system_size""])); + const ecell4::Real3 edge_lengths(L, L, L); + const ecell4::Integer3 matrix_sizes(3, 3, 3); + const ecell4::Real volume(L * L * L); + + std::shared_ptr + model(new ecell4::NetworkModel()); + + if(key_missing(input, ""DA"")){return 1;} + if(key_missing(input, ""RA"")){return 1;} + ecell4::Species sp1(std::string(""A""), input[""RA""], input[""DA""]); + model->add_species_attribute(sp1); + + if(key_missing(input, ""DB"")){return 1;} + if(key_missing(input, ""RB"")){return 1;} + ecell4::Species sp2(std::string(""B""), input[""RB""], input[""DB""]); + model->add_species_attribute(sp2); + + if(key_missing(input, ""DC"")){return 1;} + if(key_missing(input, ""RC"")){return 1;} + ecell4::Species sp3(std::string(""C""), input[""RC""], input[""DC""]); + model->add_species_attribute(sp3); + + if(key_missing(input, ""k_bind"")) {return 1;} + if(key_missing(input, ""k_unbind"")){return 1;} + const ecell4::Real k_bind = boost::lexical_cast(input[""k_bind""]); + const ecell4::Real k_unbind = boost::lexical_cast(input[""k_unbind""]); + + model->add_reaction_rule(ecell4::create_binding_reaction_rule(sp2, sp3, sp1, k_bind)); + model->add_reaction_rule(ecell4::create_unbinding_reaction_rule(sp1, sp2, sp3, k_unbind)); + + std::shared_ptr rng = + std::make_shared(); + if(key_missing(input, ""seed"")){return 1;} + rng->seed(boost::lexical_cast(input[""seed""])); + + std::shared_ptr world = + std::make_shared(edge_lengths, matrix_sizes, polygon, rng); + + if(key_missing(input, ""num_A"")){return 1;} + if(key_missing(input, ""num_B"")){return 1;} + if(key_missing(input, ""num_C"")){return 1;} + world->add_molecules(sp1, boost::lexical_cast(input[""num_A""])); + world->add_molecules(sp2, boost::lexical_cast(input[""num_B""])); + world->add_molecules(sp3, boost::lexical_cast(input[""num_C""])); + + if(key_missing(input, ""trajectory"")){return 1;} + if(key_missing(input, ""species"")) {return 1;} + if(key_missing(input, ""reaction"")) {return 1;} + std::ofstream traj(input[""trajectory""].c_str()); + std::ofstream spec(input[""species""].c_str()); + std::ofstream reac(input[""reaction""].c_str()); + if(!traj.good()) + { + std::cerr << ""file open error: "" << input[""trajecotry""] << std::endl; + return 1; + } + if(!spec.good()) + { + std::cerr << ""file open error: "" << input[""species""] << std::endl; + return 1; + } + if(!reac.good()) + { + std::cerr << ""file open error: "" << input[""reaction""] << std::endl; + return 1; + } + + if(key_missing(input, ""bd_dt"")) {return 1;} + if(key_missing(input, ""reaction_length"")){return 1;} + if(key_missing(input, ""log_file"")) {return 1;} + simulator_type sim(world, model, + boost::lexical_cast(input[""bd_dt""]), + boost::lexical_cast(input[""reaction_length""]), + input[""log_file""]); + SGFRD_TRACE(std::cerr << ""log_file = "" << input[""log_file""] << std::endl;) + SGFRD_TRACE(std::cerr << ""bd_dt = "" + << boost::lexical_cast(input[""bd_dt""]) << std::endl;) + SGFRD_TRACE(std::cerr << ""reaction_len = "" + << boost::lexical_cast(input[""reaction_length""]) << std::endl;) + sim.initialize(); + + snapshot_output(traj, world); + species_output(spec, world, sp1, sp2, sp3); + + if(key_missing(input, ""output_dt"")){return 1;} + if(key_missing(input, ""gfrd_step"")){return 1;} + const ecell4::Real dt = boost::lexical_cast(input[""output_dt""]); + const std::size_t num_step = boost::lexical_cast(input[""gfrd_step""]); + for(std::size_t i=0; i +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +void snapshot_output(std::ofstream& outstr, + const std::shared_ptr& world) +{ + typedef ecell4::sgfrd::SGFRDWorld::particle_container_type container; + container const ps = world->list_particles(); + for(container::const_iterator iter = ps.begin(); iter != ps.end(); ++iter) + { + outstr << world->t() << ' ' + << iter->second.species().serial() << ' ' + << iter->second.position()[0] << ' ' + << iter->second.position()[1] << ' ' + << iter->second.position()[2] << '\n'; + } + outstr << ""\n\n"" << std::flush; + return; +} + +void species_output(std::ofstream& outstr, + const std::shared_ptr& world, + const ecell4::Species& sp1, const ecell4::Species& sp2) +{ + outstr << world->t() << ' ' + << world->num_molecules(sp1) << ' ' + << world->num_molecules(sp2) << std::endl; + return; +} + +template +void reaction_output(std::ofstream& outstr, const SimulatorT& sim) +{ + typedef typename SimulatorT::reaction_rule_type reaction_rule_type; + typedef typename SimulatorT::reaction_info_type reaction_info_type; + typedef std::vector > + reaction_record_type; + + reaction_record_type const& rr = sim.last_reactions(); + for(typename reaction_record_type::const_iterator + iter = rr.begin(), end_ = rr.end(); iter != end_; ++iter) + { + outstr << ""rule: "" << iter->first.as_string() << "" : ""; + outstr << ""t = "" << std::setprecision(17) << iter->second.t() + << "", reactant = { ""; + for(typename reaction_info_type::container_type::const_iterator + r_iter = iter->second.reactants().begin(), + r_end = iter->second.reactants().end(); r_iter != r_end; ++r_iter) + { + outstr << r_iter->first; + } + outstr << ""}, products = { ""; + for(typename reaction_info_type::container_type::const_iterator + p_iter = iter->second.products().begin(), + p_end = iter->second.products().end(); p_iter != p_end; ++p_iter) + { + outstr << p_iter->first; + } + outstr << '}' << std::endl; + } + + return; +} + + +bool key_missing( + std::map const& inp, std::string const& key) +{ + if(inp.count(key) != 1) + { + std::cerr << ""missing key "" << key << "" in input file"" << std::endl; + return true; + } + return false; +} + +int main(int argc, char **argv) +{ + typedef ecell4::Polygon polygon_type; + typedef ecell4::sgfrd::SGFRDWorld world_type; + typedef ecell4::sgfrd::BDSimulator simulator_type; +// typedef ecell4::sgfrd::SGFRDSimulator simulator_type; + + if(argc != 2) + { + std::cerr << ""Usage: "" << argv[0] << "" input.inp"" << std::endl; + return 1; + } + + // ----------------------------------------------------------------- + // read input file + const std::string inpname(argv[1]); + std::cout << ""input file = "" << inpname << std::endl; + + std::ifstream ifs(inpname.c_str()); + if(!ifs.good()) + { + std::cerr << ""file open error: "" << inpname << std::endl; + return 1; + } + + std::map input; + while(!ifs.eof()) + { + std::string line; + std::getline(ifs, line); + if(line.empty() || line[0] == '#') {continue;} + + std::istringstream iss(line); + std::string key, equal, value; + iss >> key >> equal >> value; + if(equal != ""="") + { + std::cerr << ""invalid line in input file: "" << line << std::endl; + return 1; + } + input.insert(std::make_pair(key, value)); + ifs.peek(); + } + + // ----------------------------------------------------------------- + // setup world, model, and simulator + + if(key_missing(input, ""system_size"")){return 1;} + const ecell4::Real L(boost::lexical_cast(input[""system_size""])); + const ecell4::Real3 edge_lengths(L, L, L); + const ecell4::Integer3 matrix_sizes(3, 3, 3); + const ecell4::Real volume(L * L * L); + + if(key_missing(input, ""polygon"")){return 1;} + std::shared_ptr polygon = std::make_shared( + polygon_type(edge_lengths, ecell4::read_stl_format( + input[""polygon""], ecell4::STLFormat::Ascii)) + ); + + const std::vector fids = polygon->list_face_ids(); + + std::shared_ptr model(new ecell4::NetworkModel()); + + // A + B -> B, irreversible + + if(key_missing(input, ""DA"")){return 1;} + if(key_missing(input, ""RA"")){return 1;} + const ecell4::Real RA = boost::lexical_cast(input[""RA""]); + const ecell4::Real DA = boost::lexical_cast(input[""DA""]); + ecell4::Species sp1(std::string(""A""), RA, DA); + model->add_species_attribute(sp1); + + if(key_missing(input, ""DB"")){return 1;} + if(key_missing(input, ""RB"")){return 1;} + const ecell4::Real RB = boost::lexical_cast(input[""RB""]); + const ecell4::Real DB = boost::lexical_cast(input[""DB""]); + ecell4::Species sp2(std::string(""B""), RB, DB); + model->add_species_attribute(sp2); + + if(key_missing(input, ""k_bind"")) {return 1;} + const ecell4::Real k_bind = boost::lexical_cast(input[""k_bind""]); + model->add_reaction_rule(ecell4::create_binding_reaction_rule(sp1, sp2, sp2, k_bind)); + + std::shared_ptr rng = + std::make_shared(); + if(key_missing(input, ""seed"")){return 1;} + rng->seed(boost::lexical_cast(input[""seed""])); + + std::shared_ptr world = + std::make_shared(edge_lengths, matrix_sizes, polygon, rng); + + // ----------------------------------------------------------------- + // put particle that are in contact with each other. + const ecell4::Triangle face = polygon->triangle_at(fids.front()); + const ecell4::Real3 com = + (face.vertex_at(0) + face.vertex_at(1) + face.vertex_at(2)) / 3.0; + + // XXX assuming planer surface along 0,0 to 10,10 + const ecell4::Real safety = 1.0 + 1e-6; + const ecell4::Real distA_safety = RA * safety * std::sqrt(0.5); + const ecell4::Real distB_safety = RB * safety * std::sqrt(0.5); + + ecell4::::FaceID fid_A = fids.front(); + ecell4::::FaceID fid_B = fids.front(); + ecell4::Real3 pos_A = com + ecell4::Real3(distA_safety, distA_safety, 0); + ecell4::Real3 pos_B = com - ecell4::Real3(distB_safety, distB_safety, 0); + + std::cout << std::setprecision(17) << ecell4::length(pos_A - pos_B) << "" > "" << RA+RB << std::endl; + + + // move particle once to remove the effect of reaction volume. + // here, assuming the polygon is planer surface. + bool move_A; + if(DA <= 0.0 && DB <= 0.0) + { + std::cerr << ""[error] neither particle moves"" << std::endl; + return 1; + } + else if(DA == 0.0 && DB > 0.0) + { + move_A = false; + } + else if(DA == 0.0 && DB > 0.0) + { + move_A = true; + } + else + { + move_A = (rng->uniform_int(0, 1) == 0); + } + + + // read dt + if(key_missing(input, ""output_dt"")){return 1;} + const ecell4::Real dt = boost::lexical_cast(input[""output_dt""]); + + // this code here does not consider the curvature of the surface of the polygon + // (assuming the polygon is an ideal planner surface) + if(move_A) + { + const ecell4::Real sqrt2Dt = std::sqrt(2 * DA * dt); + const ecell4::Real3 disp(rng->gaussian(sqrt2Dt), rng->gaussian(sqrt2Dt), 0.0); + + if(length(pos_A + disp - pos_B) > (RA + RB) * safety) + { + std::tie(pos_A, fid_A) = ecell4::polygon::travel( + *polygon, std::make_pair(pos_A, fid_A), disp); + } + } + else // move_B + { + const ecell4::Real sqrt2Dt = std::sqrt(2 * DB * dt); + const ecell4::Real3 disp(rng->gaussian(sqrt2Dt), rng->gaussian(sqrt2Dt), 0.0); + + if(length(pos_B + disp - pos_A) > (RA + RB) * safety) + { + std::tie(pos_B, fid_B) = ecell4::polygon::travel( + *polygon, std::make_pair(pos_B, fid_B), disp); + } + } + + // assign particle + world->new_particle(ecell4::Particle(sp1, pos_A, RA, DA), fid_A); + world->new_particle(ecell4::Particle(sp2, pos_B, RB, DB), fid_B); + + // ----------------------------------------------------------------- + // open and clear output files + + if(key_missing(input, ""trajectory"")){return 1;} + if(key_missing(input, ""species"")) {return 1;} + if(key_missing(input, ""reaction"")) {return 1;} + std::ofstream traj(input[""trajectory""].c_str()); + std::ofstream spec(input[""species""].c_str()); + std::ofstream reac(input[""reaction""].c_str()); + if(!traj.good()) + { + std::cerr << ""file open error: "" << input[""trajecotry""] << std::endl; + return 1; + } + if(!spec.good()) + { + std::cerr << ""file open error: "" << input[""species""] << std::endl; + return 1; + } + if(!reac.good()) + { + std::cerr << ""file open error: "" << input[""reaction""] << std::endl; + return 1; + } + + // ----------------------------------------------------------------- + // build simulator + + if(key_missing(input, ""bd_dt"")) {return 1;} + if(key_missing(input, ""reaction_length"")){return 1;} + if(key_missing(input, ""log_file"")) {return 1;} + simulator_type sim(world, model, + boost::lexical_cast(input[""bd_dt""]), + boost::lexical_cast(input[""reaction_length""]), + input[""log_file""]); + SGFRD_TRACE(std::cerr << ""log_file = "" << input[""log_file""] << std::endl;) + sim.initialize(); + + // ----------------------------------------------------------------- + // run simulation + + if(key_missing(input, ""gfrd_step"")){return 1;} + const std::size_t num_step = boost::lexical_cast(input[""gfrd_step""]); + for(std::size_t i=0; inum_molecules(sp1) == 0) {break;} + } + if(world->num_molecules(sp1) == 0) {break;} + + assert(sim.next_event_time() > i * dt); + sim.finalize(i * dt); + + std::cerr << ""current t = "" << i*dt << std::endl; + + snapshot_output(traj, world); + species_output(spec, world, sp1, sp2); + reac.close(); + reac.open(input[""reaction""].c_str(), std::ios::trunc); + reaction_output(reac, sim); + + sim.initialize(); + } + sim.finalize(); + snapshot_output(traj, world); + species_output(spec, world, sp1, sp2); + + reac.close(); + reac.open(input[""reaction""].c_str(), std::ios::trunc); + reaction_output(reac, sim); + + return 0; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/samples/reaction.cpp",".cpp","10245","267","#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +void snapshot_output(std::ofstream& outstr, + const std::shared_ptr& world) +{ + typedef ecell4::sgfrd::SGFRDWorld::particle_container_type container; + container const ps = world->list_particles(); + for(container::const_iterator iter = ps.begin(); iter != ps.end(); ++iter) + { + outstr << world->t() << ' ' + << iter->second.species().serial() << ' ' + << iter->second.position()[0] << ' ' + << iter->second.position()[1] << ' ' + << iter->second.position()[2] << '\n'; + } + outstr << ""\n\n"" << std::flush; + return; +} + +void species_output(std::ofstream& outstr, + const std::shared_ptr& world, + const ecell4::Species& sp1, const ecell4::Species& sp2, + const ecell4::Species& sp3) +{ + outstr << world->t() << ' ' + << world->num_molecules(sp1) << ' ' + << world->num_molecules(sp2) << ' ' + << world->num_molecules(sp3) << std::endl; + return; +} + +void reaction_output( + std::ofstream& outstr, const ecell4::sgfrd::SGFRDSimulator& sim) +{ + typedef ecell4::sgfrd::SGFRDSimulator::reaction_rule_type reaction_rule_type; + typedef ecell4::sgfrd::SGFRDSimulator::reaction_info_type reaction_info_type; + typedef std::vector > + reaction_record_type; + + reaction_record_type const& rr = sim.last_reactions(); + for(reaction_record_type::const_iterator iter = rr.begin(), end_ = rr.end(); + iter != end_; ++iter) + { + outstr << ""rule: "" << iter->first.as_string() << "" : ""; + outstr << ""t = "" << std::setprecision(17) << iter->second.t() + << "", reactant = { ""; + for(reaction_info_type::container_type::const_iterator + r_iter = iter->second.reactants().begin(), + r_end = iter->second.reactants().end(); r_iter != r_end; ++r_iter) + { + outstr << r_iter->first; + } + outstr << ""}, products = { ""; + for(reaction_info_type::container_type::const_iterator + p_iter = iter->second.products().begin(), + p_end = iter->second.products().end(); p_iter != p_end; ++p_iter) + { + outstr << p_iter->first; + } + outstr << '}' << std::endl; + } + + return; +} + + +bool key_missing( + std::map const& inp, std::string const& key) +{ + if(inp.count(key) != 1) + { + std::cerr << ""missing key "" << key << "" in input file"" << std::endl; + return true; + } + return false; +} + +int main(int argc, char **argv) +{ + typedef ecell4::Polygon polygon_type; + typedef ecell4::sgfrd::SGFRDWorld world_type; + typedef ecell4::sgfrd::SGFRDSimulator simulator_type; + + if(argc != 2) + { + std::cerr << ""Usage: "" << argv[0] << "" input.inp"" << std::endl; + return 1; + } + + const std::string inpname(argv[1]); + std::ifstream ifs(inpname.c_str()); + if(!ifs.good()) + { + std::cerr << ""file open error: "" << inpname << std::endl; + return 1; + } + + std::map input; + while(!ifs.eof()) + { + std::string line; + std::getline(ifs, line); + if(line.empty() || line[0] == '#') continue; + + std::istringstream iss(line); + std::string key, equal, value; + iss >> key >> equal >> value; + if(equal != ""="") + { + std::cerr << ""invalid line in input file: "" << line << std::endl; + return 1; + } + input.insert(std::make_pair(key, value)); + ifs.peek(); + } + + if(key_missing(input, ""system_size"")) return 1; + const ecell4::Real L(boost::lexical_cast(input[""system_size""])); + const ecell4::Real3 edge_lengths(L, L, L); + const ecell4::Integer3 matrix_sizes(3, 3, 3); + const ecell4::Real volume(L * L * L); + + + std::shared_ptr + model(new ecell4::NetworkModel()); + + if(key_missing(input, ""DA"")){return 1;} + if(key_missing(input, ""RA"")){return 1;} + ecell4::Species sp1(std::string(""A""), boost::lexical_cast(input[""RA""]), boost::lexical_cast(input[""DA""])); + model->add_species_attribute(sp1); + if(key_missing(input, ""DB"")){return 1;} + if(key_missing(input, ""RB"")){return 1;} + ecell4::Species sp2(std::string(""B""), boost::lexical_cast(input[""RB""]), boost::lexical_cast(input[""DB""])); + model->add_species_attribute(sp2); + if(key_missing(input, ""DC"")){return 1;} + if(key_missing(input, ""RC"")){return 1;} + ecell4::Species sp3(std::string(""C""), boost::lexical_cast(input[""RC""]), boost::lexical_cast(input[""DC""])); + model->add_species_attribute(sp3); + + if(key_missing(input, ""k_bind"")) {return 1;} + if(key_missing(input, ""k_unbind"")){return 1;} + const ecell4::Real k_bind = boost::lexical_cast(input[""k_bind""]), + k_unbind = boost::lexical_cast(input[""k_unbind""]); + + model->add_reaction_rule(ecell4::create_binding_reaction_rule(sp2, sp3, sp1, k_bind)); + model->add_reaction_rule(ecell4::create_unbinding_reaction_rule(sp1, sp2, sp3, k_unbind)); + + std::shared_ptr rng = + std::make_shared(); + if(key_missing(input, ""seed"")){return 1;} + rng->seed(boost::lexical_cast(input[""seed""])); + + if(key_missing(input, ""polygon"")){return 1;} + std::shared_ptr world = std::make_shared( + edge_lengths, matrix_sizes, rng, input[""polygon""], ecell4::STLFormat::Ascii); + + if(key_missing(input, ""num_A"")){return 1;} + if(key_missing(input, ""num_B"")){return 1;} + if(key_missing(input, ""num_C"")){return 1;} + world->add_molecules(sp1, boost::lexical_cast(input[""num_A""])); + world->add_molecules(sp2, boost::lexical_cast(input[""num_B""])); + world->add_molecules(sp3, boost::lexical_cast(input[""num_C""])); + + if(key_missing(input, ""trajectory"")){return 1;} + if(key_missing(input, ""species"")) {return 1;} + if(key_missing(input, ""reaction"")) {return 1;} + std::ofstream traj(input[""trajectory""].c_str()); + std::ofstream spec(input[""species""].c_str()); + std::ofstream reac(input[""reaction""].c_str()); + if(!traj.good()) + { + std::cerr << ""file open error: "" << input[""trajecotry""] << std::endl; + return 1; + } + if(!spec.good()) + { + std::cerr << ""file open error: "" << input[""species""] << std::endl; + return 1; + } + if(!reac.good()) + { + std::cerr << ""file open error: "" << input[""reaction""] << std::endl; + return 1; + } + + if(key_missing(input, ""bd_dt"")) {return 1;} + if(key_missing(input, ""reaction_length"")){return 1;} + if(key_missing(input, ""log_file"")) {return 1;} + simulator_type sim(world, model, + boost::lexical_cast(input[""bd_dt""]), + boost::lexical_cast(input[""reaction_length""]), + input[""log_file""]); + SGFRD_TRACE(std::cerr << ""log_file = "" << input[""log_file""] << std::endl;) + sim.initialize(); + + snapshot_output(traj, world); + species_output(spec, world, sp1, sp2, sp3); + + if(key_missing(input, ""output_dt"")){return 1;} + if(key_missing(input, ""gfrd_step"")){return 1;} + const ecell4::Real dt = boost::lexical_cast(input[""output_dt""]); + const std::size_t num_step = boost::lexical_cast(input[""gfrd_step""]); + for(std::size_t i=0; i i * dt); + sim.finalize(i * dt); + + snapshot_output(traj, world); + species_output(spec, world, sp1, sp2, sp3); + reac.close(); + reac.open(input[""reaction""].c_str(), std::ios::trunc); + reaction_output(reac, sim); + + sim.initialize(); + } + sim.finalize(); + snapshot_output(traj, world); + species_output(spec, world, sp1, sp2, sp3); + + reac.close(); + reac.open(input[""reaction""].c_str(), std::ios::trunc); + reaction_output(reac, sim); + + std::cerr << ""STAT: reason for forming multi:\n""; + std::cerr << ""Single Concical Shell Failed: "" + << sim.stat_multi_reason.show_percent(ecell4::sgfrd::SingleConicalFailed) << '\n'; + std::cerr << ""Pair Shell Failed : "" + << sim.stat_multi_reason.show_percent(ecell4::sgfrd::PairFailed) << '\n'; + std::cerr << '\n'; + std::cerr << ""STAT: fired events: total = "" << sim.stat_fired_events.total() << '\n'; + std::cerr << ""Single Circular: "" + << sim.stat_fired_events.show_percent(ecell4::sgfrd::FireSingleCircular) << '\n'; + std::cerr << ""Single Conical : "" + << sim.stat_fired_events.show_percent(ecell4::sgfrd::FireSingleConical) << '\n'; + std::cerr << ""Pair : "" + << sim.stat_fired_events.show_percent(ecell4::sgfrd::FirePair) << '\n'; + std::cerr << ""Multi : "" + << sim.stat_fired_events.show_percent(ecell4::sgfrd::FireMulti) << '\n'; + std::cerr << ""Birth : "" + << sim.stat_fired_events.show_percent(ecell4::sgfrd::FireBirth) << '\n'; + std::cerr << '\n'; + std::cerr << ""STAT: formed multi size:\n""; + const std::vector ks = sim.stat_multi_size.list_all_kinds(); + for(typename std::vector::const_iterator + i(ks.begin()), e(ks.end()); i!=e; ++i) + { + std::cerr << std::setw(8) << *i << "" : "" + << sim.stat_multi_size.show_percent(*i) << '\n'; + } + std::cerr << std::flush; + + return 0; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/sgfrd/samples/diffusion.cpp",".cpp","3688","106","#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +void trajectory_output(const std::vector& pids, + const std::shared_ptr& world) +{ + for(std::vector::const_iterator + iter = pids.begin(); iter != pids.end(); ++iter) + { + std::cout << world->t() << ' ' + << world->get_particle(*iter).second.position()[0] << ' ' + << world->get_particle(*iter).second.position()[1] << ' ' + << world->get_particle(*iter).second.position()[2] << '\n'; + } + std::cout << ""\n\n""; + return; +} + +int main(int argc, char **argv) +{ + typedef ecell4::sgfrd::polygon_traits polygon_traits; + typedef ecell4::Polygon polygon_type; + typedef ecell4::sgfrd::SGFRDWorld world_type; + typedef ecell4::sgfrd::SGFRDSimulator simulator_type; + typedef polygon_type::face_id_type face_id_type; + + if(argc != 4) + { + std::cerr << ""Usage: "" << argv[0] + << "" "" + << std::endl; + return 1; + } + + const std::string stlname(argv[1]); + ecell4::STLFileReader reader; + ecell4::STLPolygonAdapter adapter; + std::shared_ptr polygon = + adapter.make_polygon(reader.read(stlname, ecell4::STLFileReader::Ascii)); + + const ecell4::Real L(boost::lexical_cast(std::string(argv[2]))); + const ecell4::Real3 edge_lengths(L, L, L); + const ecell4::Integer3 matrix_sizes(3, 3, 3); + const ecell4::Real volume(L * L * L); + + std::shared_ptr + model(new ecell4::NetworkModel()); + + ecell4::Species sp1(std::string(""A""), + /* radius = */ std::string(""1.e-2""), + /* D = */ std::string(""1.e-2"")); + model->add_species_attribute(sp1); + + std::shared_ptr rng = + std::make_shared(); + rng->seed((unsigned long int)123456); + + std::shared_ptr world = + std::make_shared(edge_lengths, matrix_sizes, polygon, rng); + + const std::size_t num_particle = polygon->num_triangles(); + + const std::vector fids = polygon->list_face_id(); + std::vector pids; pids.reserve(num_particle); + + for(std::size_t np = 0; np < num_particle; ++np) + { + ecell4::Particle p(sp1, ecell4::centroid(polygon->triangle_at(fids.at(np))), + 1e-2, 1e-2); + + //TODO add world::new_particle(Species, pos) + const std::pair, bool> newp = + world->new_particle(p, fids.at(np)); + assert(newp.second); + pids.push_back(newp.first.first); + } + + simulator_type sim(world, model); + sim.initialize(); + trajectory_output(pids, world); + + const ecell4::Real dt = 0.001; + const std::size_t num_step = boost::lexical_cast(std::string(argv[3])); + for(std::size_t i=0; i +#include + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace ecell4 +{ + +namespace bd +{ + +struct MoleculeInfo +{ + const Real radius; + const Real D; +}; + +class BDWorld + : public WorldInterface +{ +public: + + typedef MoleculeInfo molecule_info_type; + typedef ParticleSpaceCellListImpl particle_space_type; + // typedef ParticleSpaceVectorImpl particle_space_type; + typedef particle_space_type::particle_container_type particle_container_type; + +public: + + BDWorld(const Real3& edge_lengths = Real3(1, 1, 1), + const Integer3& matrix_sizes = Integer3(3, 3, 3)) + : ps_(new particle_space_type(edge_lengths, matrix_sizes)) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); + } + + BDWorld( + const Real3& edge_lengths, const Integer3& matrix_sizes, + std::shared_ptr rng) + : ps_(new particle_space_type(edge_lengths, matrix_sizes)), rng_(rng) + { + ; + } + + BDWorld(const std::string& filename) + : ps_(new particle_space_type(Real3(1, 1, 1))) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + this->load(filename); + } + + /** + * create and add a new particle + * @param p a particle + * @return a pair of a pair of pid (a particle id) and p (a particle) + * and bool (if it's succeeded or not) + */ + std::pair, bool> + new_particle(const Particle& p) + { + ParticleID pid(pidgen_()); + // if (has_particle(pid)) + // { + // throw AlreadyExists(""particle already exists""); + // } + if (list_particles_within_radius(p.position(), p.radius()).size() == 0) + { + (*ps_).update_particle(pid, p); //XXX: DONOT call this->update_particle + return std::make_pair(std::make_pair(pid, p), true); + } + else + { + return std::make_pair(std::make_pair(pid, p), false); + } + } + + std::pair, bool> + new_particle(const Species& sp, const Real3& pos) + { + const MoleculeInfo info(get_molecule_info(sp)); + return new_particle(Particle(sp, pos, info.radius, info.D)); + } + + /** + * draw attributes of species and return it as a molecule info. + * @param sp a species + * @return info a molecule info + */ + MoleculeInfo get_molecule_info(const Species& sp) const + { + Real radius(0.0), D(0.0); + + if (sp.has_attribute(""radius"") && sp.has_attribute(""D"")) + { + radius = sp.get_attribute_as(""radius""); + D = sp.get_attribute_as(""D""); + } + else if (std::shared_ptr bound_model = lock_model()) + { + Species newsp(bound_model->apply_species_attributes(sp)); + if (newsp.has_attribute(""radius"") + && newsp.has_attribute(""D"")) + { + radius = newsp.get_attribute_as(""radius""); + D = newsp.get_attribute_as(""D""); + } + } + + if (radius <= 0.0) + { + std::stringstream msg; + msg << ""A particle with invalid size ["" << radius << ""] was given.""; + throw IllegalArgument(msg.str()); + } + + MoleculeInfo info = {radius, D}; + return info; + } + + const Real t() const + { + return (*ps_).t(); + } + + void set_t(const Real& t) + { + (*ps_).set_t(t); + } + + const Real3& edge_lengths() const + { + return (*ps_).edge_lengths(); + } + + Integer num_particles() const + { + return (*ps_).num_particles(); + } + + Integer num_particles(const Species& species) const + { + return (*ps_).num_particles(species); + } + + Integer num_particles_exact(const Species& species) const + { + return (*ps_).num_particles_exact(species); + } + + bool has_particle(const ParticleID& pid) const + { + return (*ps_).has_particle(pid); + } + + std::vector > list_particles() const + { + return (*ps_).list_particles(); + } + + std::vector > + list_particles(const Species& sp) const + { + return (*ps_).list_particles(sp); + } + + std::vector > + list_particles_exact(const Species& sp) const + { + return (*ps_).list_particles_exact(sp); + } + + std::vector list_species() const + { + return (*ps_).list_species(); + } + + virtual Real get_value(const Species& sp) const + { + return static_cast(num_molecules(sp)); + } + + virtual Real get_value_exact(const Species& sp) const + { + return static_cast(num_molecules_exact(sp)); + } + + bool update_particle_without_checking(const ParticleID& pid, const Particle& p) + { + return (*ps_).update_particle(pid, p); + } + + bool update_particle(const ParticleID& pid, const Particle& p) + { + if (list_particles_within_radius(p.position(), p.radius(), pid).size() + == 0) + { + return (*ps_).update_particle(pid, p); + } + else + { + return true; + } + } + + std::pair + get_particle(const ParticleID& pid) const + { + return (*ps_).get_particle(pid); + } + + void remove_particle(const ParticleID& pid) + { + (*ps_).remove_particle(pid); + } + + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius) const + { + return (*ps_).list_particles_within_radius(pos, radius); + } + + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, const ParticleID& ignore) const + { + return (*ps_).list_particles_within_radius(pos, radius, ignore); + } + + std::vector, Real> > + list_particles_within_radius( + const Real3& pos, const Real& radius, + const ParticleID& ignore1, const ParticleID& ignore2) const + { + return (*ps_).list_particles_within_radius(pos, radius, ignore1, ignore2); + } + + inline Real3 periodic_transpose( + const Real3& pos1, const Real3& pos2) const + { + return (*ps_).periodic_transpose(pos1, pos2); + } + + inline Real3 apply_boundary(const Real3& pos) const + { + return (*ps_).apply_boundary(pos); + } + + inline Real distance_sq(const Real3& pos1, const Real3& pos2) const + { + return (*ps_).distance_sq(pos1, pos2); + } + + inline Real distance(const Real3& pos1, const Real3& pos2) const + { + return (*ps_).distance(pos1, pos2); + } + + Integer num_molecules(const Species& sp) const + { + return (*ps_).num_molecules(sp); + } + + Integer num_molecules_exact(const Species& sp) const + { + return (*ps_).num_molecules_exact(sp); + } + + void add_molecules(const Species& sp, const Integer& num) + { + extras::throw_in_particles(*this, sp, num, rng()); + } + + void add_molecules(const Species& sp, const Integer& num, const std::shared_ptr shape) + { + extras::throw_in_particles(*this, sp, num, shape, rng()); + } + + void remove_molecules(const Species& sp, const Integer& num) + { + if (num < 0) + { + throw std::invalid_argument( + ""The number of molecules must be positive.""); + } + + std::vector > + particles(list_particles(sp)); + const Integer num_particles(particles.size()); + if (num_particles < num) + { + throw std::invalid_argument( + ""The number of molecules cannot be negative.""); + } + + shuffle((*rng_), particles); + for (std::vector >::const_iterator + i(particles.begin()); i != particles.begin() + num; ++i) + { + remove_particle((*i).first); + } + } + + const Real volume() const + { + const Real3& lengths(edge_lengths()); + return lengths[0] * lengths[1] * lengths[2]; + } + + inline std::shared_ptr& rng() + { + return rng_; + } + + const particle_container_type& particles() const + { + return (*ps_).particles(); + } + + void save(const std::string& filename) const + { +#ifdef WITH_HDF5 + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + rng_->save(fout.get()); + pidgen_.save(fout.get()); + std::unique_ptr + group(new H5::Group(fout->createGroup(""ParticleSpace""))); + ps_->save_hdf5(group.get()); + extras::save_version_information(fout.get(), std::string(""ecell4-bd-"") + std::string(VERSION_INFO)); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void load(const std::string& filename) + { +#ifdef WITH_HDF5 + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-bd-0.0""; + try + { + const std::string version = extras::load_version_information(*fin); + if (!extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required << ""] or later is required.""; + throw NotSupported(ss.str()); + } + } + catch(H5::GroupIException not_found_error) + { + throw NotFound(""No version information was found.""); + } + + const H5::Group group(fin->openGroup(""ParticleSpace"")); + ps_->load_hdf5(group); + pidgen_.load(*fin); + rng_->load(*fin); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void bind_to(std::shared_ptr model) + { + if (std::shared_ptr bound_model = lock_model()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to BDWorld"" + << std::endl; + } + } + + model_ = model; + } + + std::shared_ptr lock_model() const + { + return model_.lock(); + } + +protected: + + std::unique_ptr ps_; + std::shared_ptr rng_; + SerialIDGenerator pidgen_; + + std::weak_ptr model_; +}; + +} // bd + +} // ecell4 + +#endif /* ECELL4_BD_BD_WORLD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/BDSimulator.cpp",".cpp","2532","107","#include ""BDSimulator.hpp"" + +#include + +namespace ecell4 +{ + +namespace bd +{ + +void BDSimulator::attempt_synthetic_reaction(const ReactionRule& rr) +{ + assert(rr.reactants().size() == 0); + + const Real pacc = rr.k() * (*world_).volume() * dt(); //XXX: dt must be small enough + assert(pacc <= 1); + // const Real pacc = 1.0 - exp(-rr.k() * (*world_).volume() * dt()); + const Real rnd = rng()->uniform(0, 1); + if (rnd >= pacc) + { + return; + } + + reaction_info_type::container_type new_particle_ids; + + { + for (ReactionRule::product_container_type::const_iterator i(rr.products().begin()); + i != rr.products().end(); ++i) + { + const Real3 newpos( + rng()->uniform(0, (*world_).edge_lengths()[0]), + rng()->uniform(0, (*world_).edge_lengths()[1]), + rng()->uniform(0, (*world_).edge_lengths()[2])); + std::pair, bool> + ret = (*world_).new_particle((*i), newpos); + if (ret.second) + { + new_particle_ids.push_back(ret.first); + } + else + { + for (reaction_info_type::container_type::const_iterator + j(new_particle_ids.begin()); j != new_particle_ids.end(); ++j) + { + (*world_).remove_particle((*j).first); + } + return; + } + } + } + + reaction_info_type ri(t() + dt(), reaction_info_type::container_type(), new_particle_ids); + last_reactions_.push_back(std::make_pair(rr, ri)); +} + +void BDSimulator::step() +{ + last_reactions_.clear(); + + for (Model::reaction_rule_container_type::const_iterator i((*model_).reaction_rules().begin()); + i != (*model_).reaction_rules().end(); ++i) + { + if ((*i).reactants().size() == 0) + { + attempt_synthetic_reaction(*i); + } + } + + { + BDPropagator propagator(*model_, *world_, *rng(), dt(), last_reactions_); + while (propagator()) + { + ; // do nothing here + } + } + + set_t(t() + dt()); + num_steps_++; +} + +bool BDSimulator::step(const Real& upto) +{ + const Real t0(t()), dt0(dt()), tnext(next_time()); + + if (upto <= t0) + { + return false; + } + + if (upto >= tnext) + { + step(); + return true; + } + else + { + dt_ = upto - t0; + step(); + dt_ = dt0; + return false; + } +} + +} // bd + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/functions3d.cpp",".cpp","4162","155","#include +#include + +#include ""functions3d.hpp"" + + +namespace ecell4 +{ + +namespace bd +{ + +Real3 random_spherical_uniform( + RandomNumberGenerator& rng, const Real& r) +{ + Real a(0), b(0), r2(1); + while (r2 > 0.25) + { + a = rng.uniform(0, 1) - 0.5; + b = rng.uniform(0, 1) - 0.5; + r2 = a * a + b * b; + } + + const Real scale(8 * r * std::sqrt(0.25 - r2)); + return Real3(a * scale, b * scale, r * (8 * r2 - 1)); +} + +Real3 random_displacement_3d( + RandomNumberGenerator& rng, const Real& t, const Real& D) +{ + const Real sigma(std::sqrt(2 * D * t)); + return Real3( + rng.gaussian(sigma), rng.gaussian(sigma), rng.gaussian(sigma)); +} + +Real Igbd_3d(const Real& sigma, const Real& t, const Real& D) +{ + const Real sqrtPi(std::sqrt(M_PI)); + + const Real Dt(D * t); + const Real Dt2(Dt + Dt); + const Real sqrtDt(std::sqrt(Dt)); + const Real sigmasq(sigma * sigma); + + const Real term1(1 / (3 * sqrtPi)); + const Real term2(sigmasq - Dt2); + const Real term3(Dt2 - 3 * sigmasq); + const Real term4(sqrtPi * sigmasq * sigma * gsl_sf_erfc(sigma / sqrtDt)); + + const Real result( + term1 * (-sqrtDt * (term2 * std::exp(-sigmasq / Dt) + term3) + term4)); + return result; +} + +Real Igbd_r_3d(Real r, Real sigma, Real t, Real D) +{ + const Real sqrtPi(std::sqrt(M_PI)); + + const Real Dt(D * t); + const Real Dt2(Dt + Dt); + const Real Dt4(Dt2 + Dt2); + const Real sqrtDt(std::sqrt(Dt)); + // const Real sqrtDt4(std::sqrt(Dt4)); + const Real sqrtDt4(2 * sqrtDt); + const Real sigmasq(sigma * sigma); + + const Real sigmacb(sigmasq * sigma); + const Real rcb(pow_3(r)); + + const Real rsigma(r * sigma); + + const Real rps_sq(pow_2(r + sigma)), rms_sq(pow_2(r - sigma)); + + const Real term1(-2 * sqrtDt / sqrtPi); + const Real term2(std::exp(-sigmasq / Dt) * (sigmasq - Dt2)); + const Real term3(-std::exp(-rps_sq / Dt4) * (rms_sq + rsigma - Dt2)); + const Real term4(std::exp(-rms_sq / Dt4) * (rps_sq - rsigma - Dt2)); + const Real term5(-sigmasq * 3 + Dt2); + + const Real term6((sigmacb - rcb) * gsl_sf_erf((r - sigma) / sqrtDt4)); + const Real term7(-(sigmacb + sigmacb) * gsl_sf_erf(sigma / sqrtDt)); + const Real term8((sigmacb + rcb) * gsl_sf_erf((r + sigma) / sqrtDt4)); + + const Real result( + (term1 * (term2 + term3 + term4 + term5) + term6 + term7 + term8) / 6); + return result; +} + +static Real Igbd_r_3d_F(Real r, const Igbd_r_3d_params* params) +{ + return Igbd_r_3d(r, params->sigma, params->t, params->D) - params->target; +} + +Real random_ipv_length_3d( + RandomNumberGenerator& rng, const Real& sigma, const Real& t, const Real& D) +{ + const Real epsabs(1e-18), epsrel(1e-12); + + const Real ptot(Igbd_3d(sigma, t, D)); + + Igbd_r_3d_params params = {sigma, t, D, rng.uniform(0, 1) * ptot}; +#ifndef WIN32_MSC + gsl_function F = { + reinterpret_cast(&Igbd_r_3d_F), ¶ms}; +#else + gsl_function F = { + reinterpret_cast(&Igbd_r_3d_F), ¶ms}; +#endif + + Real low(sigma), high(sigma + 10 * std::sqrt(6 * D * t)); + + gsl_root_fsolver* solver(gsl_root_fsolver_alloc(gsl_root_fsolver_brent)); + gsl_root_fsolver_set(solver, &F, low, high); + + const unsigned int max_num_iter(100); + unsigned int i(0); + while (true) + { + gsl_root_fsolver_iterate(solver); + + low = gsl_root_fsolver_x_lower(solver); + high = gsl_root_fsolver_x_upper(solver); + int status(gsl_root_test_interval(low, high, epsabs, epsrel)); + + if (status == GSL_CONTINUE) + { + if (i >= max_num_iter) + { + gsl_root_fsolver_free(solver); + throw std::runtime_error(""failed to converge""); + } + } + else + { + break; + } + + ++i; + } + + gsl_root_fsolver_free(solver); + return low; +} + +Real3 random_ipv_3d( + RandomNumberGenerator& rng, const Real& sigma, const Real& t, const Real& D) +{ + const Real r(random_ipv_length_3d(rng, sigma, t, D)); + return random_spherical_uniform(rng, r); +} + +} // bd + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/BDFactory.hpp",".hpp","2102","100","#ifndef ECELL4_BD_BD_FACTORY_HPP +#define ECELL4_BD_BD_FACTORY_HPP + +#include +#include + +#include ""BDWorld.hpp"" +#include ""BDSimulator.hpp"" + + +namespace ecell4 +{ + +namespace bd +{ + +class BDFactory: + public SimulatorFactory +{ +public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef BDFactory this_type; + +public: + + BDFactory(const Integer3& matrix_sizes = default_matrix_sizes(), Real bd_dt_factor = default_bd_dt_factor()) + : base_type(), rng_(), matrix_sizes_(matrix_sizes), bd_dt_factor_(bd_dt_factor) + { + ; // do nothing + } + + virtual ~BDFactory() + { + ; // do nothing + } + + static inline const Integer3 default_matrix_sizes() + { + return Integer3(3, 3, 3); + } + + static inline const Real default_bd_dt_factor() + { + return -1.0; + } + + this_type& rng(const std::shared_ptr& rng) + { + rng_ = rng; + return (*this); + } + + inline this_type* rng_ptr(const std::shared_ptr& rng) + { + return &(this->rng(rng)); //XXX: == this + } + +protected: + + virtual world_type* create_world(const Real3& edge_lengths) const + { + if (rng_) + { + return new world_type(edge_lengths, matrix_sizes_, rng_); + } + else + { + return new world_type(edge_lengths, matrix_sizes_); + } + } + + virtual simulator_type* create_simulator( + const std::shared_ptr& w, const std::shared_ptr& m) const + { + if (bd_dt_factor_ > 0) + { + return new simulator_type(w, m, bd_dt_factor_); + } + else + { + return new simulator_type(w, m); + } + } + +protected: + + std::shared_ptr rng_; + Integer3 matrix_sizes_; + Real bd_dt_factor_; +}; + +} // bd + +} // ecell4 + +#endif /* ECELL4_BD_BD_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/BDPropagator.hpp",".hpp","3193","153","#ifndef ECELL4_BD_BD_PROPAGATOR_HPP +#define ECELL4_BD_BD_PROPAGATOR_HPP + +#include +#include + +#include ""functions3d.hpp"" +#include ""BDWorld.hpp"" + + +namespace ecell4 +{ + +namespace bd +{ + +class ReactionInfo +{ +public: + + typedef std::pair particle_id_pair_type; + typedef std::vector container_type; + +public: + + ReactionInfo( + const Real t, + const container_type& reactants, + const container_type& products) + : t_(t), reactants_(reactants), products_(products) + {} + + ReactionInfo(const ReactionInfo& another) + : t_(another.t()), reactants_(another.reactants()), products_(another.products()) + {} + + Real t() const + { + return t_; + } + + const container_type& reactants() const + { + return reactants_; + } + + void add_reactant(const particle_id_pair_type& pid_pair) + { + reactants_.push_back(pid_pair); + } + + const container_type& products() const + { + return products_; + } + + void add_product(const particle_id_pair_type& pid_pair) + { + products_.push_back(pid_pair); + } + +protected: + + Real t_; + container_type reactants_, products_; +}; + +class BDPropagator +{ +public: + + typedef ReactionInfo reaction_info_type; + +public: + + BDPropagator( + Model& model, BDWorld& world, RandomNumberGenerator& rng, const Real& dt, + std::vector >& last_reactions) + : model_(model), world_(world), rng_(rng), dt_(dt), + last_reactions_(last_reactions), max_retry_count_(1) + { + queue_ = world_.list_particles(); + shuffle(rng_, queue_); + } + + bool operator()(); + + inline Real dt() const + { + return dt_; + } + + inline RandomNumberGenerator& rng() + { + return rng_; + } + + bool attempt_reaction(const ParticleID& pid, const Particle& particle); + bool attempt_reaction( + const ParticleID& pid1, const Particle& particle1, + const ParticleID& pid2, const Particle& particle2); + + class particle_finder + : public std::unary_function, bool> + { + public: + + particle_finder(const ParticleID& pid) + : pid_(pid) + { + ; + } + + bool operator()(std::pair pid_particle_pair) + { + return (pid_particle_pair.first == pid_); + } + + protected: + + ParticleID pid_; + }; + + void remove_particle(const ParticleID& pid); + + inline Real3 draw_displacement(const Particle& particle) + { + return random_displacement_3d(rng(), dt(), particle.D()); + } + + inline Real3 draw_ipv(const Real& sigma, const Real& t, const Real& D) + { + return random_ipv_3d(rng(), sigma, t, D); + } + +protected: + + Model& model_; + BDWorld& world_; + RandomNumberGenerator& rng_; + Real dt_; + std::vector >& last_reactions_; + Integer max_retry_count_; + + BDWorld::particle_container_type queue_; +}; + +} // bd + +} // ecell4 + +#endif /* ECELL4_BD_BD_PROPAGATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/BDSimulator.hpp",".hpp","3520","156","#ifndef ECELL4_BD_BD_SIMULATOR_HPP +#define ECELL4_BD_BD_SIMULATOR_HPP + +#include + +#include +#include + +#include ""BDWorld.hpp"" +#include ""BDPropagator.hpp"" + + +namespace ecell4 +{ + +namespace bd +{ + +class BDSimulator + : public SimulatorBase +{ +public: + + typedef SimulatorBase base_type; + typedef BDPropagator::reaction_info_type reaction_info_type; + +public: + + BDSimulator( + std::shared_ptr world, std::shared_ptr model, + Real bd_dt_factor = 1e-5) + : base_type(world, model), dt_(0), bd_dt_factor_(bd_dt_factor), dt_set_by_user_(false) + { + initialize(); + } + + BDSimulator(std::shared_ptr world, Real bd_dt_factor = 1e-5) + : base_type(world), dt_(0), bd_dt_factor_(bd_dt_factor), dt_set_by_user_(false) + { + initialize(); + } + + // SimulatorTraits + + void initialize() + { + last_reactions_.clear(); + if (!dt_set_by_user_) + { + dt_ = determine_dt(); + } + } + + Real determine_dt() const + { + constexpr Real inf = std::numeric_limits::infinity(); + Real rmin(inf), Dmax(0.0); + + for (std::vector::const_iterator i(model_->species_attributes().begin()); + i != model_->species_attributes().end(); ++i) + { + const BDWorld::molecule_info_type + info(world_->get_molecule_info(*i)); + + if (rmin > info.radius) + { + rmin = info.radius; + } + if (Dmax < info.D) + { + Dmax = info.D; + } + } + + // const std::vector splist(world_->list_species()); + + // for (std::vector::const_iterator i(splist.begin()); + // i != splist.end(); ++i) + // { + // const BDWorld::molecule_info_type + // info(world_->get_molecule_info(*i)); + // if (rmin > info.radius) + // { + // rmin = info.radius; + // } + // if (Dmax < info.D) + // { + // Dmax = info.D; + // } + // } + + const Real dt(rmin < inf && Dmax > 0.0 + ? 4.0 * rmin * rmin / (2.0 * Dmax) * bd_dt_factor_ + // ? rmin * rmin / (6.0 * Dmax) * bd_dt_factor_ + : inf); + return dt; + } + + Real dt() const + { + return dt_; + } + + void step(); + bool step(const Real& upto); + + // Optional members + + virtual bool check_reaction() const + { + return last_reactions_.size() > 0; + } + + std::vector > + last_reactions() const + { + return last_reactions_; + } + + void set_dt(const Real& dt) + { + if (dt <= 0) + { + throw std::invalid_argument(""The step size must be positive.""); + } + dt_ = dt; + dt_set_by_user_ = true; + } + + inline std::shared_ptr rng() + { + return (*world_).rng(); + } + +protected: + + void attempt_synthetic_reaction(const ReactionRule& rr); + +protected: + + /** + * the protected internal state of BDSimulator. + * they are needed to be saved/loaded with Visitor pattern. + */ + Real dt_; + const Real bd_dt_factor_; + bool dt_set_by_user_; + std::vector > last_reactions_; +}; + +} // bd + +} // ecell4 + +#endif /* ECELL4_BD_BD_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/functions3d.hpp",".hpp","1706","58","#ifndef ECELL4_BD_FUNCTIONS_3D_HPP +#define ECELL4_BD_FUNCTIONS_3D_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ + +namespace bd +{ + +/** + * $\int_0^\infty r^2dr\,g\left(r,\Delta t\right),$ + * where $g\left(r,\Delta t\right)$ is a probability that a pair, which is + * initially separated by a length $r$, overlaps after the time $\Delta t$: + * $g\left(r,\Delta t\right)\equiv\int_0^\sigma r'^2dr'\int_0^\pi\sin\theta + * d\theta\int_0^{2\pi}d\phi\,p\left({\bf r'},t+\Delta t;{\bf r},t\right).$ + * see Eqs. (20-21) in (Morelli & ten Wolde, J. Chem. Phys., 2008). + * @param sigma a radius of the excluded volume, $\sigma$. + * @param t a step interval, $\Delta t$. + * @param D a diffusion coefficient, $D$. + */ +Real Igbd_3d(const Real& sigma, const Real& t, const Real& D); + +/** + * $\int_0^R r^2dr\,g\left(r,\Delta t\right).$ + * see Eqs. (20-21) in (Morelli & ten Wolde, J. Chem. Phys., 2008). + * @param an upper limit of the integration, $R$. + * @param sigma a radius of the excluded volume, $\sigma$. + * @param t a step interval, $\Delta t$. + * @param D a diffusion coefficient, $D$. + */ +Real Igbd_r_3d(Real r, Real sigma, Real t, Real D); + +Real3 random_spherical_uniform(RandomNumberGenerator& rng, const Real& r); +Real3 random_displacement_3d( + RandomNumberGenerator& rng, const Real& t, const Real& D); + +Real3 random_ipv_3d( + RandomNumberGenerator& rng, const Real& sigma, const Real& t, const Real& D); + +struct Igbd_r_3d_params +{ + const Real sigma; + const Real t; + const Real D; + const Real target; +}; + +} // bd + +} // ecell4 + +#endif /* ECELL4_BD_FUNCTIONS_3D_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/BDPropagator.cpp",".cpp","10791","305","#include + +#include +#include + +#include ""BDPropagator.hpp"" + + +namespace ecell4 +{ + +namespace bd +{ + +bool BDPropagator::operator()() +{ + if (queue_.empty()) + { + return false; + } + + const ParticleID pid(queue_.back().first); + queue_.pop_back(); + Particle particle(world_.get_particle(pid).second); + + if (attempt_reaction(pid, particle)) + { + return true; + } + + const Real D(particle.D()); + if (D == 0) + { + return true; + } + + const Real3 newpos( + world_.apply_boundary( + particle.position() + draw_displacement(particle))); + Particle particle_to_update( + particle.species(), newpos, particle.radius(), particle.D()); + // Particle particle_to_update( + // particle.species_serial(), newpos, particle.radius(), particle.D()); + std::vector, Real> > + overlapped(world_.list_particles_within_radius( + newpos, particle.radius(), pid)); + + switch (overlapped.size()) + { + case 0: + world_.update_particle_without_checking(pid, particle_to_update); + return true; + case 1: + { + std::pair closest( + (*(overlapped.begin())).first); + if (attempt_reaction( + pid, particle_to_update, closest.first, closest.second)) + { + return true; + } + } + return true; + default: + return true; + } +} + +bool BDPropagator::attempt_reaction( + const ParticleID& pid, const Particle& particle) +{ + std::vector reaction_rules( + model_.query_reaction_rules(particle.species())); + if (reaction_rules.size() == 0) + { + return false; + } + + const Real rnd(rng().uniform(0, 1)); + Real prob(0); + for (std::vector::const_iterator i(reaction_rules.begin()); + i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + prob += rr.k() * dt(); + if (prob > rnd) + { + const ReactionRule::product_container_type& products(rr.products()); + reaction_info_type ri(world_.t() + dt_, reaction_info_type::container_type(1, std::make_pair(pid, particle)), reaction_info_type::container_type()); + + switch (products.size()) + { + case 0: + remove_particle(pid); + last_reactions_.push_back(std::make_pair(rr, ri)); + break; + case 1: + { + const Species species_new( + model_.apply_species_attributes(*(products.begin()))); + const BDWorld::molecule_info_type + info(world_.get_molecule_info(species_new)); + const Real radius_new(info.radius); + const Real D_new(info.D); + + std::vector, Real> > + overlapped(world_.list_particles_within_radius( + particle.position(), radius_new, pid)); + if (overlapped.size() > 0) + { + // throw NoSpace(""""); + return false; + } + + Particle particle_to_update( + species_new, particle.position(), radius_new, D_new); + world_.update_particle(pid, particle_to_update); + + ri.add_product(std::make_pair(pid, particle_to_update)); + last_reactions_.push_back(std::make_pair(rr, ri)); + } + break; + case 2: + { + ReactionRule::product_container_type::const_iterator + it(products.begin()); + const Species species_new1( + model_.apply_species_attributes(*it)); + const Species species_new2( + model_.apply_species_attributes(*(++it))); + + const BDWorld::molecule_info_type + info1(world_.get_molecule_info(species_new1)), + info2(world_.get_molecule_info(species_new2)); + const Real radius1(info1.radius), + radius2(info2.radius); + const Real D1(info1.D), D2(info2.D); + + const Real D12(D1 + D2); + const Real r12(radius1 + radius2); + Real3 newpos1, newpos2; + Integer i(max_retry_count_); + while (true) + { + if (--i < 0) + { + // throw NoSpace("""") + return false; + } + + const Real3 ipv(draw_ipv(r12, dt(), D12)); + + newpos1 = world_.apply_boundary( + particle.position() + ipv * (D1 / D12)); + newpos2 = world_.apply_boundary( + particle.position() - ipv * (D2 / D12)); + std::vector< + std::pair, Real> > + overlapped1(world_.list_particles_within_radius( + newpos1, radius1, pid)); + std::vector< + std::pair, Real> > + overlapped2(world_.list_particles_within_radius( + newpos2, radius2, pid)); + if (overlapped1.size() == 0 && overlapped2.size() == 0) + { + break; + } + } + + Particle particle_to_update1( + species_new1, newpos1, radius1, D1); + Particle particle_to_update2( + species_new2, newpos2, radius2, D2); + world_.update_particle(pid, particle_to_update1); + std::pair, bool> retval = world_.new_particle(particle_to_update2); + + ri.add_product(std::make_pair(pid, particle_to_update1)); + ri.add_product(retval.first); + last_reactions_.push_back(std::make_pair(rr, ri)); + } + break; + default: + throw NotImplemented( + ""more than two products are not allowed""); + break; + } + return true; + } + } + + return false; +} + +bool BDPropagator::attempt_reaction( + const ParticleID& pid1, const Particle& particle1, + const ParticleID& pid2, const Particle& particle2) +{ + std::vector reaction_rules( + model_.query_reaction_rules( + particle1.species(), particle2.species())); + if (reaction_rules.size() == 0) + { + return false; + } + + const Real D1(particle1.D()), D2(particle2.D()); + const Real r12(particle1.radius() + particle2.radius()); + const Real rnd(rng().uniform(0, 1)); + Real prob(0); + + for (std::vector::const_iterator i(reaction_rules.begin()); + i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + prob += rr.k() * dt() / ( + (Igbd_3d(r12, dt(), D1) + Igbd_3d(r12, dt(), D2)) * 4 * M_PI); + + if (prob >= 1) + { + // throw std::runtime_error( + // ""the total reaction probability exceeds 1."" + // "" the step interval is too long""); + std::cerr << + ""the total reaction probability exceeds 1."" + "" the step interval is too long"" << std::endl; + } + if (prob > rnd) + { + const ReactionRule::product_container_type& products(rr.products()); + reaction_info_type ri(world_.t() + dt_, reaction_info_type::container_type(1, std::make_pair(pid1, particle1)), reaction_info_type::container_type()); + ri.add_reactant(std::make_pair(pid2, particle2)); + + switch (products.size()) + { + case 0: + remove_particle(pid1); + remove_particle(pid2); + + last_reactions_.push_back(std::make_pair(rr, ri)); + break; + case 1: + { + const Species sp(*(products.begin())); + const BDWorld::molecule_info_type + info(world_.get_molecule_info(sp)); + const Real radius_new(info.radius); + const Real D_new(info.D); + + const Real3 pos1(particle1.position()); + const Real3 pos2( + world_.periodic_transpose(particle2.position(), pos1)); + const Real D1(particle1.D()), D2(particle2.D()); + const Real D12(D1 + D2); + const Real3 newpos( + world_.apply_boundary((pos1 * D2 + pos2 * D1) / D12)); + + std::vector, Real> > + overlapped(world_.list_particles_within_radius( + newpos, radius_new, pid1, pid2)); + if (overlapped.size() > 0) + { + // throw NoSpace(""""); + return false; + } + + const Particle particle_to_update( + sp, newpos, radius_new, D_new); + remove_particle(pid2); + // world_.update_particle(pid1, particle_to_update); + remove_particle(pid1); + std::pair, bool> retval = world_.new_particle(particle_to_update); + + ri.add_product(retval.first); + last_reactions_.push_back(std::make_pair(rr, ri)); + } + break; + default: + throw NotImplemented( + ""more than one product is not allowed""); + break; + } + return true; + } + } + + return false; +} + +void BDPropagator::remove_particle(const ParticleID& pid) +{ + world_.remove_particle(pid); + particle_finder cmp(pid); + std::vector >::iterator + i(std::find_if(queue_.begin(), queue_.end(), cmp)); + if (i != queue_.end()) + { + queue_.erase(i); + } +} + +} // bd + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/samples/hardbody.cpp",".cpp","1896","69","#include + +#include +#include +#include +#include + +#include + +using namespace ecell4; +using namespace ecell4::bd; + +/** + * a simple function to dump particle position(s) + */ +void print_particle_position(const BDWorld& world, const ParticleID& pid) +{ + const Real3 pos(world.get_particle(pid).second.position()); + std::cout << std::setprecision(12) << world.t() << "" : "" << pos << std::endl; +} + +/** + * main function + */ +int main(int argc, char** argv) +{ + /// simulation parameters + const Real L(1e-6); + std::string D(""5e-12""), radius(""5e-9""); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(3, 3, 3); + + /// instantiate NetworkModel + std::shared_ptr model(new NetworkModel()); + + /// create a Species, and set its attributes + Species sp1(""A""); + sp1.set_attribute(""D"", D); + sp1.set_attribute(""radius"", radius); + (*model).add_species_attribute(sp1); + + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + /// instantiate BDWorld + std::shared_ptr world(new BDWorld(edge_lengths, matrix_sizes, rng)); + world->bind_to(model); + + /// create a Particle, and inject it into BDWorld + BDWorld::molecule_info_type info1((*world).get_molecule_info(Species(""A""))); + const Particle p1( + sp1, Real3(0, 0, 0), info1.radius, info1.D); + const ParticleID pid1((*world).new_particle(p1).first.first); + world->save(""test_bd.h5""); + + /// instatiate BDSimulator + BDSimulator sim(world, model); + sim.set_dt(1e-6); + + /// run and log by the millisecond + for (unsigned int i(0); i <= 10; ++i) + { + while (sim.step(1e-3 * i)) + { + ; // do nothing + } + print_particle_position(*world, pid1); + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/tests/BDWorld_test.cpp",".cpp","1062","42","#define BOOST_TEST_MODULE ""BDWorld_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include ""../BDWorld.hpp"" + +using namespace ecell4; +using namespace ecell4::bd; + + +BOOST_AUTO_TEST_CASE(BDWorld_test_constructor) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(3, 3, 3); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + BDWorld target(edge_lengths, matrix_sizes, rng); +} + +BOOST_AUTO_TEST_CASE(BDWorld_test_edge_lengths) +{ + const Real L(1e-6); + const Real3 input(L, L, L); + const Integer3 matrix_sizes(3, 3, 3); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + BDWorld target(input, matrix_sizes, rng); + + const Real3& output(target.edge_lengths()); + for (Real3::size_type dim(0); dim < 3; ++dim) + { + BOOST_CHECK(output[dim] > 0); + BOOST_CHECK_EQUAL(output[dim], input[dim]); + } +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/bd/tests/BDSimulator_test.cpp",".cpp","1821","62","#define BOOST_TEST_MODULE ""BDSimulator_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include ""../BDSimulator.hpp"" + +using namespace ecell4; +using namespace ecell4::bd; + + +BOOST_AUTO_TEST_CASE(BDSimulator_test_constructor) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(3, 3, 3); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + std::shared_ptr model(new NetworkModel()); + std::shared_ptr world(new BDWorld(edge_lengths, matrix_sizes, rng)); + + BDSimulator target(world, model); +} + +BOOST_AUTO_TEST_CASE(BDSimulator_test_step1) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(3, 3, 3); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + std::shared_ptr model(new NetworkModel()); + std::shared_ptr world(new BDWorld(edge_lengths, matrix_sizes, rng)); + + BDSimulator target(world, model); + target.step(); +} + +BOOST_AUTO_TEST_CASE(BDSimulator_test_step2) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Integer3 matrix_sizes(3, 3, 3); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + + std::shared_ptr model(new NetworkModel()); + Species sp1(""A"", 2.5e-9, 1e-12); + model->add_species_attribute(sp1); + + std::shared_ptr world(new BDWorld(edge_lengths, matrix_sizes, rng)); + world->new_particle(Particle(sp1, Real3(0, 0, 0), 2.5e-9, 1e-12)); + world->add_molecules(sp1, 10); + + BDSimulator target(world, model); + target.step(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/ode.cpp",".cpp","4453","117","#include ""python_api.hpp"" + +#include +#include +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +using namespace ecell4::ode; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline +void define_ode_factory(py::module& m) +{ + py::class_ factory(m, ""ODEFactory""); + factory + .def(py::init(), + py::arg(""solver_type"") = ODEFactory::default_solver_type(), + py::arg(""dt"") = ODEFactory::default_dt(), + py::arg(""abs_tol"") = ODEFactory::default_abs_tol(), + py::arg(""rel_tol"") = ODEFactory::default_rel_tol()) + .def(""rng"", &ODEFactory::rng); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline +void define_ode_simulator(py::module& m) +{ + py::class_, + std::shared_ptr> simulator(m, ""ODESimulator""); + simulator + .def(py::init&, const ODESolverType>(), + py::arg(""w""), + py::arg(""solver_type"") = ODESolverType::ROSENBROCK4_CONTROLLER) + .def(py::init&, const std::shared_ptr&, const ODESolverType>(), + py::arg(""w""), py::arg(""m""), + py::arg(""solver_type"") = ODESolverType::ROSENBROCK4_CONTROLLER) + .def(""set_t"", &ODESimulator::set_t) + .def(""absolute_tolerance"", &ODESimulator::absolute_tolerance) + .def(""maximum_step_interval"", &ODESimulator::maximum_step_interval) + .def(""set_maximum_step_interval"", &ODESimulator::set_maximum_step_interval) + .def(""set_relative_tolerance"", &ODESimulator::set_relative_tolerance) + .def(""relative_tolerance"", &ODESimulator::relative_tolerance) + .def(""set_absolute_tolerance"", &ODESimulator::set_absolute_tolerance) + .def(""values"", &ODESimulator::values) + .def(""derivatives"", &ODESimulator::derivatives) + .def(""jacobian"", &ODESimulator::jacobian) + .def(""fluxes"", &ODESimulator::fluxes) + .def(""elasticity"", &ODESimulator::elasticity) + .def(""stoichiometry"", &ODESimulator::stoichiometry); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline +void define_ode_world(py::module& m) +{ + py::class_, + std::shared_ptr> world(m, ""ODEWorld""); + world + .def(py::init(), py::arg(""edge_lengths"") = Real3(1.0, 1.0, 1.0)) + .def(py::init(), py::arg(""filename"")) + .def(""set_volume"", &ODEWorld::set_volume) + .def(""new_particle"", + (std::pair, bool> + (ODEWorld::*)(const Particle&)) &ODEWorld::new_particle) + .def(""new_particle"", + (std::pair, bool> + (ODEWorld::*)(const Species&, const Real3&)) &ODEWorld::new_particle) + .def(""add_molecules"", + (void (ODEWorld::*)(const Species&, const Real&)) &ODEWorld::add_molecules) + .def(""add_molecules"", + (void (ODEWorld::*)(const Species&, const Integer&, const std::shared_ptr)) &ODEWorld::add_molecules) + .def(""remove_molecules"", &ODEWorld::remove_molecules) + .def(""set_value"", &ODEWorld::set_value) + .def(""reserve_species"", &ODEWorld::reserve_species) + .def(""release_species"", &ODEWorld::release_species) + .def(""bind_to"", &ODEWorld::bind_to) + .def(""get_values"", &ODEWorld::get_values) + .def(""evaluate"", + (std::vector + (ODEWorld::*)(const std::vector&) const) &ODEWorld::evaluate) + .def(""evaluate"", + (Real + (ODEWorld::*)(const ReactionRule&) const) &ODEWorld::evaluate); + + m.attr(""World"") = world; +} + +void setup_ode_module(py::module& m) +{ + py::enum_(m, ""ODESolverType"") + .value(""RUNGE_KUTTA_CASH_KARP54"", ODESolverType::RUNGE_KUTTA_CASH_KARP54) + .value(""ROSENBROCK4_CONTROLLER"", ODESolverType::ROSENBROCK4_CONTROLLER) + .value(""EULER"", ODESolverType::EULER) + .export_values(); + + define_ode_factory(m); + define_ode_simulator(m); + define_ode_world(m); +} + +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/sgfrd.cpp",".cpp","8538","200","#include ""python_api.hpp"" + +#include +#include +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; + +namespace ecell4 +{ +namespace python_api +{ + +// TODO: enable to read polygon from python function + +static inline +void define_sgfrd_factory(py::module& m) +{ + using factory_type = ::ecell4::sgfrd::SGFRDFactory; + + py::class_ factory(m, ""SGFRDFactory""); + factory + .def(py::init(), + py::arg(""matrix_sizes"") = factory_type::default_matrix_sizes(), + py::arg(""bd_dt_factor"") = factory_type::default_bd_dt_factor(), + py::arg(""bd_reaction_length_factor"") = factory_type::default_bd_reaction_length_factor()) + .def(""rng"", &factory_type::rng) + .def(""polygon"", (factory_type& (factory_type::*)(const Real3&, const std::vector&))&factory_type::polygon) + .def(""polygon"", (factory_type& (factory_type::*)(const std::string&, const STLFormat)) &factory_type::polygon); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline +void define_sgfrd_simulator(py::module& m) +{ + using factory_type = ::ecell4::sgfrd::SGFRDFactory; + using world_type = ::ecell4::sgfrd::SGFRDWorld; + using simulator_type = ::ecell4::sgfrd::SGFRDSimulator; + + py::class_, + std::shared_ptr + > simulator(m, ""SGFRDSimulator""); + simulator + .def(py::init, Real, Real>(), + py::arg(""w""), + py::arg(""bd_dt_factor"") = factory_type::default_bd_dt_factor(), + py::arg(""bd_reaction_length_factor"") = factory_type::default_bd_reaction_length_factor()) + .def(py::init, std::shared_ptr, Real, Real>(), + py::arg(""w""), + py::arg(""m""), + py::arg(""bd_dt_factor"") = factory_type::default_bd_dt_factor(), + py::arg(""bd_reaction_length_factor"") = factory_type::default_bd_reaction_length_factor()) + .def(""last_reactions"", &simulator_type::last_reactions) + .def(""set_t"", &simulator_type::set_t); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline +void define_sgfrd_world(py::module& m) +{ + using world_type = ::ecell4::sgfrd::SGFRDWorld; + + py::class_, + std::shared_ptr> world(m, ""SGFRDWorld""); + world + .def(py::init(), + py::arg(""edge_lengths"") = Real3(1.0, 1.0, 1.0), + py::arg(""matrix_sizes"") = Integer3(1, 1, 1)) + .def(py::init>(), + py::arg(""edge_lengths""), + py::arg(""matrix_sizes""), + py::arg(""rng"")) + .def(py::init(), + py::arg(""edge_lengths""), + py::arg(""matrix_sizes""), + py::arg(""stl_file""), + py::arg(""stl_format"")) + .def(py::init, + const std::string&, const STLFormat>(), + py::arg(""edge_lengths""), + py::arg(""matrix_sizes""), + py::arg(""rng""), + py::arg(""stl_file""), + py::arg(""stl_format"")) + .def(py::init(), py::arg(""filename"")) + .def(""polygon"", &world_type::polygon) + .def(""new_particle"", + (std::pair, bool> (world_type::*)(const Particle&)) + &world_type::new_particle) + .def(""new_particle"", + (std::pair, bool> (world_type::*)(const Species&, const Real3&)) + &world_type::new_particle) + .def(""new_particle"", + (std::pair, bool> + (world_type::*)(const Species&, const FaceID&, const Barycentric&)) + &world_type::new_particle) + .def(""new_particle"", + (std::pair, bool> + (world_type::*)(const Species&, const std::pair&)) + &world_type::new_particle) + .def(""update_particle"", + (bool (world_type::*)(const ParticleID&, const Particle&)) + &world_type::update_particle) + .def(""remove_particle"", + (void (world_type::*)(const ParticleID&)) + &world_type::remove_particle) + .def(""list_particles_within_radius"", + (std::vector, Real>> + (world_type::*)(const Real3&, const Real&) const) + &world_type::list_particles_within_radius) + .def(""list_particles_within_radius"", + (std::vector, Real>> + (world_type::*)(const Real3&, const Real&, const ParticleID&) const) + &world_type::list_particles_within_radius) + .def(""list_particles_within_radius"", + (std::vector, Real>> + (world_type::*)(const Real3&, const Real&, const ParticleID&, const ParticleID&) const) + &world_type::list_particles_within_radius) + .def(""periodic_transpose"", &world_type::periodic_transpose) + .def(""apply_boundary"", &world_type::apply_boundary) + .def(""distance_sq"", + (Real (world_type::*)(const Real3&, const Real3&)) + &world_type::distance_sq) + .def(""distance"", + (Real (world_type::*)(const Real3&, const Real3&)) + &world_type::distance) + .def(""add_molecules"", + (void (world_type::*)(const Species&, const Integer&)) + &world_type::add_molecules) + .def(""add_molecules"", + (void (world_type::*)(const Species&, const Integer&, const std::shared_ptr)) + &world_type::add_molecules) + .def(""remove_molecules"", &world_type::remove_molecules) + + .def(""get_triangle"", &world_type::get_triangle) + .def(""get_surface_position"", &world_type::get_surface_position) + .def(""list_surface_positions"", + (std::vector>> + (world_type::*)() const) + &world_type::list_surface_positions) + .def(""list_surface_positions"", + (std::vector>> + (world_type::*)(const Species&) const) + &world_type::list_surface_positions) + .def(""list_surface_positions_exact"", &world_type::list_surface_positions_exact) + .def(""bind_to"", &world_type::bind_to) + .def(""rng"", (std::shared_ptr& (world_type::*)()) + &world_type::rng); + m.attr(""World"") = world; +} + +static inline +void define_reaction_info(py::module& m) +{ + using reaction_info_type = ::ecell4::sgfrd::ReactionInfo; + using container_type = reaction_info_type::container_type; + + py::class_(m, ""ReactionInfo"") + .def(py::init(), + py::arg(""t""), py::arg(""reactants""), py::arg(""products"")) + .def(""t"", &reaction_info_type::t) + .def(""reactants"", &reaction_info_type::reactants) + .def(""products"", &reaction_info_type::products) + .def(py::pickle( + [](const reaction_info_type& self) + { + return py::make_tuple(self.t(), self.reactants(), self.products()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return reaction_info_type( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); +} + +void setup_sgfrd_module(py::module& m) +{ + define_sgfrd_factory(m); + define_sgfrd_simulator(m); + define_sgfrd_world(m); + define_reaction_info(m); +} + +} // python_api +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/shape.hpp",".hpp","2355","90","#ifndef ECELL4_PYTHON_API_SHAPE_HPP +#define ECELL4_PYTHON_API_SHAPE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + + template + class PyShape: public Base + { + public: + using Base::Base; + using dimension_kind = Shape::dimension_kind; + + dimension_kind dimension() const override + { + PYBIND11_OVERLOAD_PURE(dimension_kind, Base, dimension,); + } + + Real is_inside(const Real3& coord) const override + { + PYBIND11_OVERLOAD_PURE(Real, Base, is_inside, coord); + } + + Real3 draw_position(std::shared_ptr& rng) const override + { + PYBIND11_OVERLOAD_PURE(Real3, Base, draw_position, rng); + } + + bool test_AABB(const Real3& l, const Real3& u) const override + { + PYBIND11_OVERLOAD_PURE(bool, Base, test_AABB, l, u); + } + + void bounding_box(const Real3& edge_lengths, Real3& lower, Real3& upper) const override + { + PYBIND11_OVERLOAD(void, Base, bounding_box, edge_lengths, lower, upper); + } + }; + + template + class PyShapeImpl: public PyShape + { + public: + using PyShape::PyShape; + using dimension_kind = Shape::dimension_kind; + + dimension_kind dimension() const override + { + PYBIND11_OVERLOAD(dimension_kind, Base, dimension,); + } + + Real is_inside(const Real3& coord) const override + { + PYBIND11_OVERLOAD(Real, Base, is_inside, coord); + } + + Real3 draw_position(std::shared_ptr& rng) const override + { + PYBIND11_OVERLOAD(Real3, Base, draw_position, rng); + } + + bool test_AABB(const Real3& l, const Real3& u) const override + { + PYBIND11_OVERLOAD(bool, Base, test_AABB, l, u); + } + }; + +} + +} + +#endif /* ECELL4_PYTHON_API_SHAPE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/gillespie.cpp",".cpp","3897","118","#include ""python_api.hpp"" + +#include +#include +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +using namespace ecell4::gillespie; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline +void define_gillespie_factory(py::module& m) +{ + py::class_ factory(m, ""GillespieFactory""); + factory + .def(py::init<>()) + .def(""rng"", &GillespieFactory::rng); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline +void define_gillespie_simulator(py::module& m) +{ + py::class_, + std::shared_ptr> simulator(m, ""GillespieSimulator""); + simulator + .def(py::init>(), py::arg(""w"")) + .def(py::init, std::shared_ptr>(), + py::arg(""w""), py::arg(""m"")) + .def(""last_reactions"", &GillespieSimulator::last_reactions) + .def(""set_t"", &GillespieSimulator::set_t); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline +void define_gillespie_world(py::module& m) +{ + py::class_, + std::shared_ptr> world(m, ""GillespieWorld""); + world + .def(py::init(), py::arg(""edge_lengths"") = Real3(1.0, 1.0, 1.0)) + .def(py::init>(), + py::arg(""edge_lengths""), py::arg(""rng"")) + .def(py::init(), py::arg(""filename"")) + .def(""set_value"", &GillespieWorld::set_value) + .def(""add_molecules"", + (void (GillespieWorld::*)(const Species&, const Integer&)) + &GillespieWorld::add_molecules) + .def(""add_molecules"", + (void (GillespieWorld::*)(const Species&, const Integer&, const std::shared_ptr)) + &GillespieWorld::add_molecules) + .def(""remove_molecules"", &GillespieWorld::remove_molecules) + .def(""new_particle"", + (std::pair, bool> (GillespieWorld::*)(const Particle&)) + &GillespieWorld::new_particle) + .def(""new_particle"", + (std::pair, bool> (GillespieWorld::*)(const Species&, const Real3&)) + &GillespieWorld::new_particle) + .def(""bind_to"", &GillespieWorld::bind_to) + .def(""rng"", &GillespieWorld::rng); + + m.attr(""World"") = world; +} + +static inline +void define_reaction_info(py::module& m) +{ + using container_type = ReactionInfo::container_type; + + py::class_(m, ""ReactionInfo"") + .def(py::init(), + py::arg(""t""), py::arg(""reactants""), py::arg(""products"")) + .def(""t"", &ReactionInfo::t) + .def(""reactants"", &ReactionInfo::reactants) + .def(""products"", &ReactionInfo::products) + .def(py::pickle( + [](const ReactionInfo& self) + { + return py::make_tuple(self.t(), self.reactants(), self.products()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return ReactionInfo( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); +} + +void setup_gillespie_module(py::module& m) +{ + define_gillespie_factory(m); + define_gillespie_simulator(m); + define_gillespie_world(m); + define_reaction_info(m); +} + +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/simulator.hpp",".hpp","2727","129","#ifndef ECELL4_PYTHON_API_SIMULATOR_HPP +#define ECELL4_PYTHON_API_SIMULATOR_HPP + +#include +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + +template +class PySimulator : public Base +{ +public: + using Base::Base; + + void initialize() override + { + PYBIND11_OVERLOAD_PURE(void, Base, initialize,); + } + + Real t() const override + { + PYBIND11_OVERLOAD_PURE(Real, Base, t,); + } + + Real dt() const override + { + PYBIND11_OVERLOAD_PURE(Real, Base, dt,); + } + + void set_dt(const Real& dt) override + { + PYBIND11_OVERLOAD_PURE(void, Base, set_dt, dt); + } + + Integer num_steps() const override + { + PYBIND11_OVERLOAD_PURE(Integer, Base, num_steps,); + } + + void step() override + { + PYBIND11_OVERLOAD_PURE(void, Base, step,); + } + + bool step(const Real& upto) override + { + PYBIND11_OVERLOAD_PURE(bool, Base, step, upto); + } + + bool check_reaction() const override + { + PYBIND11_OVERLOAD(bool, Base, check_reaction,); + } +}; + +template +class PySimulatorImpl : public PySimulator +{ +public: + + using PySimulator::PySimulator; + + void initialize() override + { + PYBIND11_OVERLOAD(void, Base, initialize,); + } + + Real t() const override + { + PYBIND11_OVERLOAD(Real, Base, t,); + } + + Real dt() const override + { + PYBIND11_OVERLOAD(Real, Base, dt,); + } + + void set_dt(const Real& dt) override + { + PYBIND11_OVERLOAD(void, Base, set_dt, dt); + } + + Integer num_steps() const override + { + PYBIND11_OVERLOAD(Integer, Base, num_steps,); + } + + void step() override + { + PYBIND11_OVERLOAD(void, Base, step,); + } + + bool step(const Real& upto) override + { + PYBIND11_OVERLOAD(bool, Base, step, upto); + } +}; + +template +static inline +void define_simulator_functions(py::class_& simulator) +{ + simulator + .def(""model"", &S::model) + .def(""world"", &S::world) + .def(""run"", + (void (S::*)(const Real&, const bool)) &S::run, + py::arg(""duration""), py::arg(""is_dirty"") = true) + .def(""run"", + (void (S::*)(const Real&, const std::shared_ptr&, const bool)) &S::run, + py::arg(""duration""), py::arg(""observer""), py::arg(""is_dirty"") = true) + .def(""run"", + (void (S::*)(const Real&, std::vector>, const bool)) &S::run, + py::arg(""duration""), py::arg(""observers""), py::arg(""is_dirty"") = true) + ; +} + +} + +} + +#endif /* ECELL4_PYTHON_API_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/spatiocyte.cpp",".cpp","9276","222","#include ""python_api.hpp"" + +#include +#include +#include +#include +#include +#include +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +using namespace ecell4::spatiocyte; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline void define_reaction_info(py::module &m) +{ + using container_type = ReactionInfo::container_type; + py::class_(m, ""ReactionInfo"") + .def(py::init(), + py::arg(""t""), py::arg(""reactants""), py::arg(""products"")) + .def(""t"", &ReactionInfo::t) + .def(""reactants"", &ReactionInfo::reactants) + .def(""products"", &ReactionInfo::products) + .def(py::pickle( + [](const ReactionInfo &self) { + return py::make_tuple(self.t(), self.reactants(), + self.products()); + }, + [](py::tuple t) { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return ReactionInfo(t[0].cast(), + t[1].cast(), + t[2].cast()); + })); + + py::class_(m, ""ReactionInfoItem"") + .def_readonly(""pid"", &ReactionInfo::Item::pid) + .def_readonly(""species"", &ReactionInfo::Item::species) + .def_readonly(""voxel"", &ReactionInfo::Item::voxel); +} + +static inline void define_spatiocyte_factory(py::module &m) +{ + py::class_ factory(m, ""SpatiocyteFactory""); + factory + .def(py::init(), + py::arg(""voxel_radius"") = + SpatiocyteFactory::default_voxel_radius()) + .def(""rng"", &SpatiocyteFactory::rng); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline void define_spatiocyte_simulator(py::module &m) +{ + py::class_, + std::shared_ptr> + simulator(m, ""SpatiocyteSimulator""); + simulator.def(py::init>(), py::arg(""w"")) + .def(py::init, + std::shared_ptr>(), + py::arg(""w""), py::arg(""m"")) + .def(""last_reactions"", &SpatiocyteSimulator::last_reactions) + .def(""set_t"", &SpatiocyteSimulator::set_t); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline void define_spatiocyte_world(py::module &m) +{ + py::class_, std::shared_ptr> + world(m, ""SpatiocyteWorld""); + world + .def(py::init(), + py::arg(""edge_lengths"") = Real3(1.0, 1.0, 1.0)) + .def(py::init(), py::arg(""edge_lengths""), + py::arg(""voxel_radius"")) + .def(py::init &>(), + py::arg(""edge_lengths""), py::arg(""voxel_radius""), py::arg(""rng"")) + .def(py::init(), py::arg(""filename"")) + + .def(""new_particle"", (boost::optional(SpatiocyteWorld::*)( + const Particle &)) & + SpatiocyteWorld::new_particle) + .def(""new_particle"", (boost::optional(SpatiocyteWorld::*)( + const Species &, const Real3 &)) & + SpatiocyteWorld::new_particle) + .def(""remove_particle"", &SpatiocyteWorld::remove_particle) + .def(""list_structure_particles"", + &SpatiocyteWorld::list_structure_particles) + .def(""list_non_structure_particles"", + &SpatiocyteWorld::list_non_structure_particles) + .def(""update_particle"", &SpatiocyteWorld::update_particle) + .def(""add_molecules"", + (bool (SpatiocyteWorld::*)(const Species &, const Integer &)) & + SpatiocyteWorld::add_molecules) + .def(""add_molecules"", + (bool (SpatiocyteWorld::*)(const Species &, const Integer &, + const std::shared_ptr)) & + SpatiocyteWorld::add_molecules) + .def(""remove_molecules"", &SpatiocyteWorld::remove_molecules) + .def(""voxel_volume"", &SpatiocyteWorld::voxel_volume) + .def(""get_volume"", &SpatiocyteWorld::get_volume) + .def(""get_voxel_at"", &SpatiocyteWorld::get_voxel_at) + .def(""get_species_at"", &SpatiocyteWorld::get_species_at) + .def(""has_particle_at"", &SpatiocyteWorld::has_particle_at) + .def(""set_value"", &SpatiocyteWorld::set_value) + .def(""new_particle"", (boost::optional(SpatiocyteWorld::*)( + const Species &, const Voxel &)) & + SpatiocyteWorld::new_particle) + .def(""new_voxel"", + (boost::optional(SpatiocyteWorld::*)(const Species &, + const Voxel &)) & + SpatiocyteWorld::new_particle, + R""pbdoc( + .. deprecated::3.0 + Use :func:`new_particle` instead. + )pbdoc"") + .def(""new_voxel_structure"", &SpatiocyteWorld::new_voxel_structure) + .def(""voxel_radius"", &SpatiocyteWorld::voxel_radius) + .def(""size"", &SpatiocyteWorld::size) + .def(""shape"", &SpatiocyteWorld::shape) + .def(""bind_to"", &SpatiocyteWorld::bind_to) + .def(""get_voxel"", &SpatiocyteWorld::get_voxel) + .def(""get_voxel_nearby"", &SpatiocyteWorld::get_voxel_nearby) + .def(""get_voxel_near_by"", &SpatiocyteWorld::get_voxel_nearby, R""pbdoc( + .. deprecated:: 3.0 + Use :func:`get_voxel_nearby` instead. + )pbdoc"") + .def(""add_structure"", &SpatiocyteWorld::add_structure) + .def(""remove_voxel"", &SpatiocyteWorld::remove_particle, R""pbdoc( + .. deprecated:: 3.0 + Use :func:`remove_particle` instead. + )pbdoc"") + .def(""has_voxel"", &SpatiocyteWorld::has_particle, R""pbdoc( + .. deprecated:: 3.0 + Use :func:`has_particle` instead. + )pbdoc"") + .def(""rng"", &SpatiocyteWorld::rng) + .def(""add_offlattice"", + [](SpatiocyteWorld &self, const Species &species, + const OffLattice &offlattice) { + const auto info = self.get_molecule_info(species); + const auto updated = Species(species.serial(), info.radius, + info.D, info.loc, info.dimension); + self.add_space(offlattice.generate_space(updated)); + }) + .def_static(""calculate_voxel_volume"", + &SpatiocyteWorld::calculate_voxel_volume) + .def_static(""calculate_hcp_lengths"", + &SpatiocyteWorld::calculate_hcp_lengths) + .def_static(""calculate_shape"", &SpatiocyteWorld::calculate_shape) + .def_static(""calculate_volume"", &SpatiocyteWorld::calculate_volume) + .def(""list_neighbors"", + [](const SpatiocyteWorld &self, const Voxel &voxel) { + std::vector list; + for (auto i = 0; i < self.num_neighbors(voxel); ++i) + { + list.push_back(self.get_neighbor(voxel, i)); + } + return list; + }); + + m.def(""create_spatiocyte_world_cell_list_impl"", + &create_spatiocyte_world_cell_list_impl); + m.def(""create_spatiocyte_world_vector_impl"", + &create_spatiocyte_world_vector_impl); + m.def(""create_spatiocyte_world_square_offlattice_impl"", + &allocate_spatiocyte_world_square_offlattice_impl); + + m.attr(""World"") = world; +} + +static inline void define_voxel(py::module &m) +{ + py::class_(m, ""Voxel"") +#ifndef NDEBUG + .def_readonly(""coordinate"", &Voxel::coordinate) +#endif + .def(""position"", &Voxel::position); +} + +static inline void define_offlattice(py::module &m) +{ + py::class_(m, ""OffLattice"") + .def(py::init()) + .def(py::init()) + .def(""voxel_radius"", &OffLattice::voxel_radius) + .def(""positions"", &OffLattice::positions) + .def(""adjoining_pairs"", &OffLattice::adjoining_pairs); +} + +void setup_spatiocyte_module(py::module &m) +{ + define_reaction_info(m); + define_offlattice(m); + define_spatiocyte_factory(m); + define_spatiocyte_simulator(m); + define_spatiocyte_world(m); + define_voxel(m); +} + +} // namespace python_api + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/world_interface.hpp",".hpp","3999","145","#ifndef ECELL4_PYTHON_API_WORLD_INTERFACE_HPP +#define ECELL4_PYTHON_API_WORLD_INTERFACE_HPP + +#include +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + + template + class PyWorldInterface: public Base + { + public: + using Base::Base; + + const Real t() const override + { + PYBIND11_OVERLOAD(const Real, Base, t,); + } + void set_t(const Real& t) override + { + PYBIND11_OVERLOAD_PURE(void, Base, set_t, t); + } + + void save(const std::string& filename) const override + { + PYBIND11_OVERLOAD_PURE(void, Base, save, filename); + } + void load(const std::string& filename) override + { + PYBIND11_OVERLOAD(void, Base, load, filename); + } + + const Real volume() const override + { + PYBIND11_OVERLOAD(const Real, Base, volume,); + } + + bool has_species(const Species& sp) const override + { + PYBIND11_OVERLOAD(bool, Base, has_species, sp); + } + + std::vector list_species() const override + { + PYBIND11_OVERLOAD(std::vector, Base, list_species,); + } + + Integer num_molecules(const Species& sp) const override + { + PYBIND11_OVERLOAD(Integer, Base, num_molecules, sp); + } + + Integer num_molecules_exact(const Species& sp) const override + { + PYBIND11_OVERLOAD(Integer, Base, num_molecules_exact, sp); + } + + Real get_value(const Species& sp) const override + { + PYBIND11_OVERLOAD(Real, Base, get_value, sp); + } + + Real get_value_exact(const Species& sp) const override + { + PYBIND11_OVERLOAD(Real, Base, get_value_exact, sp); + } + + const Real3& edge_lengths() const override + { + PYBIND11_OVERLOAD(const Real3&, Base, edge_lengths,); + } + + Integer num_particles() const override + { + PYBIND11_OVERLOAD(Integer, Base, num_particles,); + } + + Integer num_particles(const Species& sp) const override + { + PYBIND11_OVERLOAD(Integer, Base, num_particles, sp); + } + + Integer num_particles_exact(const Species& sp) const override + { + PYBIND11_OVERLOAD(Integer, Base, num_particles_exact, sp); + } + + bool has_particle(const ParticleID& pid) const override + { + PYBIND11_OVERLOAD(bool, Base, has_particle, pid); + } + + using ParticleWithID = std::pair; + std::pair get_particle(const ParticleID& pid) const override + { + PYBIND11_OVERLOAD(ParticleWithID, Base, get_particle, pid); + } + + std::vector> + list_particles() const override + { + PYBIND11_OVERLOAD(std::vector, Base, list_particles,); + } + + std::vector> + list_particles(const Species& sp) const override + { + PYBIND11_OVERLOAD(std::vector, Base, list_particles, sp); + } + + std::vector> + list_particles_exact(const Species& sp) const override + { + PYBIND11_OVERLOAD(std::vector, Base, list_particles_exact, sp); + } + }; + + template + class PyWorldImpl: public PyWorldInterface + { + public: + using PyWorldInterface::PyWorldInterface; + + void set_t(const Real& t) override + { + PYBIND11_OVERLOAD(void, Base, set_t, t); + } + + void save(const std::string& filename) const override + { + PYBIND11_OVERLOAD(void, Base, save, filename); + } + }; + +} + +} +#endif /* ECELL4_PYTHON_API_WORLD_INTERFACE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/python_api.hpp",".hpp","665","29","#ifndef ECELL4_PYTHON_API_PYTHON_API_HPP +#define ECELL4_PYTHON_API_PYTHON_API_HPP + +#include +#include +#include + +#include ""type_caster.hpp"" + +namespace ecell4 +{ + +namespace python_api +{ + +void setup_module(pybind11::module& m); +void setup_bd_module(pybind11::module& m); +void setup_egfrd_module(pybind11::module& m); +void setup_gillespie_module(pybind11::module& m); +void setup_meso_module(pybind11::module& m); +void setup_ode_module(pybind11::module& m); +void setup_sgfrd_module(pybind11::module& m); +void setup_spatiocyte_module(pybind11::module& m); + +} + +} +#endif /* ECELL4_PYTHON_API_PYTHON_API_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/meso.cpp",".cpp","7655","173","#include ""python_api.hpp"" + +#include +#include +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +using namespace ecell4::meso; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline +void define_meso_factory(py::module& m) +{ + py::class_ factory(m, ""MesoscopicFactory""); + factory + .def(py::init(), + py::arg(""matrix_sizes"") = MesoscopicFactory::default_matrix_sizes(), + py::arg(""subvolume_length"") = MesoscopicFactory::default_subvolume_length()) + .def(""rng"", &MesoscopicFactory::rng); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline +void define_meso_simulator(py::module& m) +{ + py::class_, + std::shared_ptr> simulator(m, ""MesoscopicSimulator""); + simulator + .def(py::init>(), py::arg(""w"")) + .def(py::init, std::shared_ptr>(), + py::arg(""w""), py::arg(""m"")) + .def(""last_reactions"", &MesoscopicSimulator::last_reactions) + .def(""set_t"", &MesoscopicSimulator::set_t); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline +void define_meso_world(py::module& m) +{ + using coordinate_type = MesoscopicWorld::coordinate_type; + + py::class_, + std::shared_ptr> world(m, ""MesoscopicWorld""); + world + .def(py::init(), py::arg(""edge_lengths"") = Real3(1.0, 1.0, 1.0)) + .def(py::init(), + py::arg(""edge_lengths""), py::arg(""matrix_sizes"")) + .def(py::init>(), + py::arg(""edge_lengths""), py::arg(""matrix_sizes""), py::arg(""rng"")) + .def(py::init(), + py::arg(""edge_lengths""), py::arg(""subvlume_length"")) + .def(py::init>(), + py::arg(""edge_lengths""), py::arg(""subvlume_length""), py::arg(""rng"")) + .def(py::init(), py::arg(""filename"")) + .def(""matrix_sizes"", &MesoscopicWorld::matrix_sizes) + .def(""subvolume"", &MesoscopicWorld::subvolume) + .def(""set_value"", &MesoscopicWorld::set_value) + .def(""num_subvolumes"", + (const Integer (MesoscopicWorld::*)() const) &MesoscopicWorld::num_subvolumes) + .def(""num_subvolumes"", + (const Integer (MesoscopicWorld::*)(const Species&) const) &MesoscopicWorld::num_subvolumes) + .def(""subvolume_edge_lengths"", &MesoscopicWorld::subvolume_edge_lengths) + .def(""global2coord"", &MesoscopicWorld::global2coord) + .def(""coord2global"", &MesoscopicWorld::coord2global) + .def(""position2global"", &MesoscopicWorld::position2global) + .def(""position2coordinate"", &MesoscopicWorld::position2coordinate) + .def(""num_molecules"", + (Integer (MesoscopicWorld::*)(const Species&) const) &MesoscopicWorld::num_molecules) + .def(""num_molecules"", + (Integer (MesoscopicWorld::*)(const Species&, const coordinate_type&) const) &MesoscopicWorld::num_molecules) + .def(""num_molecules"", + (Integer (MesoscopicWorld::*)(const Species&, const Integer3&) const) &MesoscopicWorld::num_molecules) + .def(""add_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&)) &MesoscopicWorld::add_molecules) + .def(""add_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&, const coordinate_type&)) &MesoscopicWorld::add_molecules) + .def(""add_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&, const Integer3&)) &MesoscopicWorld::add_molecules) + .def(""add_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&, const std::shared_ptr)) &MesoscopicWorld::add_molecules) + .def(""remove_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&)) &MesoscopicWorld::remove_molecules) + .def(""remove_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&, const Integer3&)) &MesoscopicWorld::remove_molecules) + .def(""remove_molecules"", + (void (MesoscopicWorld::*)(const Species&, const Integer&, const coordinate_type&)) &MesoscopicWorld::remove_molecules) + .def(""add_structure"", &MesoscopicWorld::add_structure) + .def(""get_volume"", &MesoscopicWorld::get_volume) + .def(""get_data"", &MesoscopicWorld::get_volume) + .def(""has_structure"", &MesoscopicWorld::has_structure) + .def(""on_structure"", + (bool (MesoscopicWorld::*)(const Species&, const Integer3&) const) + &MesoscopicWorld::on_structure) + .def(""check_structure"", + (bool (MesoscopicWorld::*)(const Species&, const Integer3&) const) + &MesoscopicWorld::check_structure) + .def(""get_occupancy"", + (Real (MesoscopicWorld::*)(const Species&, const coordinate_type&) const) + &MesoscopicWorld::get_occupancy) + .def(""get_occupancy"", + (Real (MesoscopicWorld::*)(const Species&, const Integer3&) const) + &MesoscopicWorld::get_occupancy) + .def(""list_coordinates"", &MesoscopicWorld::list_coordinates) + .def(""list_coordinates_exact"", &MesoscopicWorld::list_coordinates_exact) + .def(""new_particle"", + (std::pair, bool> (MesoscopicWorld::*)(const Particle&)) + &MesoscopicWorld::new_particle) + .def(""new_particle"", + (std::pair, bool> (MesoscopicWorld::*)(const Species&, const Real3&)) + &MesoscopicWorld::new_particle) + .def(""bind_to"", &MesoscopicWorld::bind_to) + .def(""rng"", &MesoscopicWorld::rng); + + m.attr(""World"") = world; +} + +static inline +void define_reaction_info(py::module& m) +{ + using container_type = ReactionInfo::container_type; + using coordinate_type = ReactionInfo::coordinate_type; + + py::class_(m, ""ReactionInfo"") + .def(py::init(), + py::arg(""t""), py::arg(""reactants""), py::arg(""products""), py::arg(""coord"")) + .def(""t"", &ReactionInfo::t) + .def(""coordinate"", &ReactionInfo::coordinate) + .def(""reactants"", &ReactionInfo::reactants) + .def(""products"", &ReactionInfo::products) + .def(py::pickle( + [](const ReactionInfo& self) + { + return py::make_tuple(self.t(), self.reactants(), self.products(), self.coordinate()); + }, + [](py::tuple t) + { + if (t.size() != 4) + throw std::runtime_error(""Invalid state""); + return ReactionInfo( + t[0].cast(), + t[1].cast(), + t[2].cast(), + t[3].cast() + ); + } + )); +} + +void setup_meso_module(py::module& m) +{ + define_meso_factory(m); + define_meso_simulator(m); + define_meso_world(m); + define_reaction_info(m); +} + +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/bd.cpp",".cpp","5033","139","#include ""python_api.hpp"" + +#include +#include +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +using namespace ecell4::bd; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline +void define_bd_factory(py::module& m) +{ + py::class_ factory(m, ""BDFactory""); + factory + .def(py::init(), + py::arg(""matrix_sizes"") = BDFactory::default_matrix_sizes(), + py::arg(""bd_dt_factor"") = BDFactory::default_bd_dt_factor()) + .def(""rng"", &BDFactory::rng); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline +void define_bd_simulator(py::module& m) +{ + py::class_, + std::shared_ptr> simulator(m, ""BDSimulator""); + simulator + .def(py::init, Real>(), + py::arg(""w""), py::arg(""bd_dt_factor"") = 1e-5) + .def(py::init, std::shared_ptr, Real>(), + py::arg(""w""), py::arg(""m""), py::arg(""bd_dt_factor"") = 1e-5) + .def(""last_reactions"", &BDSimulator::last_reactions) + .def(""set_t"", &BDSimulator::set_t); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline +void define_bd_world(py::module& m) +{ + py::class_, + std::shared_ptr> world(m, ""BDWorld""); + world + .def(py::init(), + py::arg(""edge_lengths"") = Real3(1.0, 1.0, 1.0), + py::arg(""matrix_sizes"") = Integer3(1, 1, 1)) + .def(py::init>(), + py::arg(""edge_lengths""), py::arg(""matrix_sizes""), py::arg(""rng"")) + .def(py::init(), py::arg(""filename"")) + + .def(""new_particle"", + (std::pair, bool> (BDWorld::*)(const Particle&)) + &BDWorld::new_particle) + .def(""new_particle"", + (std::pair, bool> (BDWorld::*)(const Species&, const Real3&)) + &BDWorld::new_particle) + .def(""update_particle"", &BDWorld::update_particle) + .def(""remove_particle"", &BDWorld::remove_particle) + .def(""list_particles_within_radius"", + (std::vector, Real>> + (BDWorld::*)(const Real3&, const Real&) const) + &BDWorld::list_particles_within_radius) + .def(""list_particles_within_radius"", + (std::vector, Real>> + (BDWorld::*)(const Real3&, const Real&, const ParticleID&) const) + &BDWorld::list_particles_within_radius) + .def(""list_particles_within_radius"", + (std::vector, Real>> + (BDWorld::*)(const Real3&, const Real&, const ParticleID&, const ParticleID&) const) + &BDWorld::list_particles_within_radius) + .def(""periodic_transpose"", &BDWorld::periodic_transpose) + .def(""apply_boundary"", &BDWorld::apply_boundary) + .def(""distance_sq"", &BDWorld::distance_sq) + .def(""distance"", &BDWorld::distance) + .def(""add_molecules"", + (void (BDWorld::*)(const Species&, const Integer&)) &BDWorld::add_molecules) + .def(""add_molecules"", + (void (BDWorld::*)(const Species&, const Integer&, const std::shared_ptr)) &BDWorld::add_molecules) + .def(""remove_molecules"", &BDWorld::remove_molecules) + .def(""bind_to"", &BDWorld::bind_to) + .def(""rng"", &BDWorld::rng); + + m.attr(""World"") = world; +} + +static inline +void define_reaction_info(py::module& m) +{ + using container_type = ReactionInfo::container_type; + + py::class_(m, ""ReactionInfo"") + .def(py::init(), + py::arg(""t""), py::arg(""reactants""), py::arg(""products"")) + .def(""t"", &ReactionInfo::t) + .def(""reactants"", &ReactionInfo::reactants) + .def(""products"", &ReactionInfo::products) + .def(py::pickle( + [](const ReactionInfo& self) + { + return py::make_tuple(self.t(), self.reactants(), self.products()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return ReactionInfo( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); +} + +void setup_bd_module(py::module& m) +{ + define_bd_factory(m); + define_bd_simulator(m); + define_bd_world(m); + define_reaction_info(m); +} + +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/main.cpp",".cpp","1228","28","#include +#include +#include ""python_api.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +using namespace ecell4::python_api; + +PYBIND11_MODULE(ecell4_base, m) { + py::module m_core = m.def_submodule(""core"", ""A submodule of ecell4_base""); + py::module m_bd = m.def_submodule(""bd"", ""A submodule of ecell4_base""); + py::module m_egfrd = m.def_submodule(""egfrd"", ""A submodule of ecell4_base""); + py::module m_gillespie = m.def_submodule(""gillespie"", ""A submodule of ecell4_base""); + py::module m_meso = m.def_submodule(""meso"", ""A submodule of ecell4_base""); + py::module m_ode = m.def_submodule(""ode"", ""A submodule of ecell4_base""); + py::module m_sgfrd = m.def_submodule(""sgfrd"", ""A submodule of ecell4_base""); + py::module m_spatiocyte = m.def_submodule(""spatiocyte"", ""A submodule of ecell4_base""); + + setup_module(m_core); + setup_bd_module(m_bd); + setup_egfrd_module(m_egfrd); + setup_gillespie_module(m_gillespie); + setup_meso_module(m_meso); + setup_ode_module(m_ode); + setup_sgfrd_module(m_sgfrd); + setup_spatiocyte_module(m_spatiocyte); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/model.hpp",".hpp","5368","162","#ifndef ECELL4_PYTHON_API_MODEL_HPP +#define ECELL4_PYTHON_API_MODEL_HPP + +#include +#include +#include +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + + template + class PyModel: public Base + { + public: + using Base::Base; + + std::vector query_reaction_rules(const Species& sp) const override + { + PYBIND11_OVERLOAD_PURE(std::vector, Base, query_reaction_rules, sp); + } + + std::vector query_reaction_rules(const Species& sp1, const Species& sp2) const override + { + PYBIND11_OVERLOAD_PURE(std::vector, Base, query_reaction_rules, sp1, sp2); + } + + bool update_species_attribute(const Species& sp) override + { + PYBIND11_OVERLOAD(bool, Base, update_species_attribute, sp); + } + + void add_species_attribute(const Species& sp, const bool proceed = false) override + { + PYBIND11_OVERLOAD(void, Base, add_species_attribute, sp, proceed); + } + + bool has_species_attribute(const Species& sp) const override + { + PYBIND11_OVERLOAD(bool, Base, has_species_attribute, sp); + } + + void remove_species_attribute(const Species& sp) override + { + PYBIND11_OVERLOAD(void, Base, remove_species_attribute, sp); + } + + Species apply_species_attributes(const Species& sp) const override + { + PYBIND11_OVERLOAD(Species, Base, apply_species_attributes, sp); + } + + void add_reaction_rule(const ReactionRule& rr) override + { + PYBIND11_OVERLOAD(void, Base, add_reaction_rule, rr); + } + + void remove_reaction_rule(const ReactionRule& rr) override + { + PYBIND11_OVERLOAD(void, Base, remove_reaction_rule, rr); + } + + bool has_reaction_rule(const ReactionRule& rr) const override + { + PYBIND11_OVERLOAD(bool, Base, has_reaction_rule, rr); + } + + const Model::reaction_rule_container_type& reaction_rules() const override + { + PYBIND11_OVERLOAD_PURE(const Model::reaction_rule_container_type&, Base, reaction_rules,); + } + + const Model::species_container_type& species_attributes() const override + { + PYBIND11_OVERLOAD_PURE(const Model::species_container_type&, Base, species_attributes,); + } + const std::vector& species_attributes_proceed() const override + { + PYBIND11_OVERLOAD_PURE(const std::vector&, Base, species_attributes_proceed,); + } + + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr, + const std::map& max_stoich) const override + { + PYBIND11_OVERLOAD_PURE(std::shared_ptr, Base, expand, sp, max_itr, max_stoich); + } + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr) const override + { + PYBIND11_OVERLOAD_PURE(std::shared_ptr, Base, expand, sp, max_itr); + } + + std::shared_ptr expand(const std::vector& sp) const override + { + PYBIND11_OVERLOAD_PURE(std::shared_ptr, Base, expand, sp); + } + }; + + template + class PyModelImpl: public PyModel + { + public: + using PyModel::PyModel; + + std::vector query_reaction_rules(const Species& sp) const override + { + PYBIND11_OVERLOAD(std::vector, Base, query_reaction_rules, sp); + } + + std::vector query_reaction_rules(const Species& sp1, const Species& sp2) const override + { + PYBIND11_OVERLOAD(std::vector, Base, query_reaction_rules, sp1, sp2); + } + + const Model::reaction_rule_container_type& reaction_rules() const override + { + PYBIND11_OVERLOAD(const Model::reaction_rule_container_type&, Base, reaction_rules,); + } + + const Model::species_container_type& species_attributes() const override + { + PYBIND11_OVERLOAD(const Model::species_container_type&, Base, species_attributes,); + } + + const std::vector& species_attributes_proceed() const override + { + PYBIND11_OVERLOAD(const std::vector&, Base, species_attributes_proceed,); + } + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr, + const std::map& max_stoich) const override + { + PYBIND11_OVERLOAD(std::shared_ptr, Base, expand, sp, max_itr, max_stoich); + } + + std::shared_ptr expand( + const std::vector& sp, const Integer max_itr) const override + { + PYBIND11_OVERLOAD(std::shared_ptr, Base, expand, sp, max_itr); + } + + std::shared_ptr expand(const std::vector& sp) const override + { + PYBIND11_OVERLOAD(std::shared_ptr, Base, expand, sp); + } + }; + +} + +} + +#endif /* ECELL4_PYTHON_API_MODEL_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/simulator_factory.hpp",".hpp","1930","65","#ifndef ECELL4_PYTHON_API_SIMULATOR_FACTORY_HPP +#define ECELL4_PYTHON_API_SIMULATOR_FACTORY_HPP + +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + +template +static inline +void define_factory_functions(py::class_& factory) +{ + using world_type = typename Factory::world_type; + using simulator_type = typename Factory::simulator_type; + + factory + .def(""world"", + [](const Factory& self, const Real3& edge_lengths) + { + return std::shared_ptr(self.world(edge_lengths)); + }, + py::arg(""edge_lengths"") = ones()) + .def(""world"", + [](const Factory& self, const Real volume) + { + return std::shared_ptr(self.world(volume)); + }, + py::arg(""volume"")) + .def(""world"", + [](const Factory& self, const std::string& filename) + { + return std::shared_ptr(self.world(filename)); + }, + py::arg(""filename"")) + .def(""world"", + [](const Factory& self, const std::shared_ptr& model) + { + return std::shared_ptr(self.world(model)); + }, + py::arg(""model"")) + .def(""simulator"", + [](const Factory& self, const std::shared_ptr& world) + { + return std::shared_ptr(self.simulator(world)); + }, + py::arg(""world"")) + .def(""simulator"", + [](const Factory& self, const std::shared_ptr& world, const std::shared_ptr& model) + { + return std::shared_ptr(self.simulator(world, model)); + }, + py::arg(""world""), py::arg(""model"")); +} + +} + +} + +#endif /* ECELL4_PYTHON_API_SIMULATOR_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/random_number_generator.hpp",".hpp","3920","165","#ifndef ECELL4_PYTHON_API_RANDOM_NUMBER_GENERATOR_HPP +#define ECELL4_PYTHON_API_RANDOM_NUMBER_GENERATOR_HPP + +#include + +namespace ecell4 +{ + +namespace python_api +{ + + template + class PyRandomNumberGenerator: public Base + { + public: + using Base::Base; + + Real random() + { + PYBIND11_OVERLOAD_PURE(Real, Base, random,); + } + + Real uniform(Real min, Real max) + { + PYBIND11_OVERLOAD_PURE(Real, Base, uniform, min, max); + } + + Integer uniform_int(Integer min, Integer max) + { + PYBIND11_OVERLOAD_PURE(Integer, Base, uniform_int, min, max); + } + + Real gaussian(Real sigma, Real mean = 0.0) + { + PYBIND11_OVERLOAD_PURE(Real, Base, gaussian, sigma, mean); + } + + Integer binomial(Real p, Integer n) + { + PYBIND11_OVERLOAD_PURE(Integer, Base, binomial, p, n); + } + + Real3 direction3d(Real length = 1.0) + { + PYBIND11_OVERLOAD_PURE(Real3, Base, direction3d, length); + } + + void seed(Integer val) + { + PYBIND11_OVERLOAD_PURE(void, Base, seed, val); + } + + void seed() + { + PYBIND11_OVERLOAD_PURE(void, Base, seed,); + } + +#ifdef WITH_HDF5 + void save(H5::H5Location* root) const + { + PYBIND11_OVERLOAD_PURE(void, Base, save, root); + } + + void load(const H5::H5Location& root) + { + PYBIND11_OVERLOAD_PURE(void, Base, load, root); + } + + void save(const std::string& filename) const + { + PYBIND11_OVERLOAD_PURE(void, Base, save, filename); + } + + void load(const std::string& filename) + { + PYBIND11_OVERLOAD_PURE(void, Base, load, filename); + } +#else + void save(const std::string& filename) const + { + PYBIND11_OVERLOAD(void, Base, save, filename); + } + + void load(const std::string& filename) + { + PYBIND11_OVERLOAD(void, Base, load, filename); + } +#endif + }; + + template + class PyRandomNumberGeneratorImpl: public PyRandomNumberGenerator + { + public: + using PyRandomNumberGenerator::PyRandomNumberGenerator; + + Real random() + { + PYBIND11_OVERLOAD(Real, Base, random,); + } + + Real uniform(Real min, Real max) + { + PYBIND11_OVERLOAD(Real, Base, uniform, min, max); + } + + Integer uniform_int(Integer min, Integer max) + { + PYBIND11_OVERLOAD(Integer, Base, uniform_int, min, max); + } + + Real gaussian(Real sigma, Real mean = 0.0) + { + PYBIND11_OVERLOAD(Real, Base, gaussian, sigma, mean); + } + + Integer binomial(Real p, Integer n) + { + PYBIND11_OVERLOAD(Integer, Base, binomial, p, n); + } + + Real3 direction3d(Real length = 1.0) + { + PYBIND11_OVERLOAD(Real3, Base, direction3d, length); + } + + void seed(Integer val) + { + PYBIND11_OVERLOAD(void, Base, seed, val); + } + + void seed() + { + PYBIND11_OVERLOAD(void, Base, seed,); + } + +#ifdef WITH_HDF5 + void save(H5::H5Location* root) const + { + PYBIND11_OVERLOAD(void, Base, save, root); + } + + void load(const H5::H5Location& root) + { + PYBIND11_OVERLOAD(void, Base, load, root); + } + + void save(const std::string& filename) const + { + PYBIND11_OVERLOAD(void, Base, save, filename); + } + + void load(const std::string& filename) + { + PYBIND11_OVERLOAD(void, Base, load, filename); + } +#endif + }; + +} // python_api + +} // ecell4 + +#endif /* ECELL4_PYTHON_API_RANDOM_NUMBER_GENERATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/core.cpp",".cpp","65786","1480","#include ""python_api.hpp"" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include ""model.hpp"" +#include ""observers.hpp"" +#include ""random_number_generator.hpp"" +#include ""reaction_rule_descriptor.hpp"" +#include ""shape.hpp"" +#include ""world_interface.hpp"" +#include ""simulator.hpp"" + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline +void define_real3(py::module& m) +{ + py::class_(m, ""Real3"") + .def(py::init(), + py::arg(""x""), py::arg(""y""), py::arg(""z"")) + .def(py::self += py::self) + .def(py::self + py::self) + .def(py::self -= py::self) + .def(py::self - py::self) + .def(py::self *= Real3::value_type()) + .def(py::self * Real3::value_type()) + .def(""__rmul__"", [](const Real3& x, Real3::value_type y) { return x * y; }, py::is_operator()) + .def(py::self /= Real3::value_type()) + .def(py::self / Real3::value_type()) + .def(""__setitem__"", + [](Real3 &x, std::size_t i, Real3::value_type value) + { + if (i >= 3) throw std::out_of_range(""""); + x.at(i) = value; + }, + py::is_operator()) + .def(""__getitem__"", + [](const Real3 &x, std::size_t i) + { + if (i >= 3) throw std::out_of_range(""""); + return x.at(i); + }, + py::is_operator()) + .def(""__abs__"", [](const Real3& x) { return abs(x); }, py::is_operator()) + .def(""__eq__"", [](const Real3& x, const Real3& y) + { + return x[0] == y[0] && x[1] == y[1] && x[2] == y[2]; + }, + py::is_operator()) + .def(py::pickle( + [](const Real3& x) + { + return py::make_tuple(x[0], x[1], x[2]); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return Real3( + t[0].cast(), + t[1].cast(), + t[2].cast()); + } + )); + + m.def(""real3_add"", (Real3 (*)(const Real3&, const Real3&)) &add); + m.def(""real3_subtract"", (Real3 (*)(const Real3&, const Real3&)) &subtract); + m.def(""real3_divide"", (Real3 (*)(const Real3&, const Real3::value_type&)) ÷); + m.def(""real3_multiply"", (Real3 (*)(const Real3&, const Real3::value_type&)) &multiply); + + m.def(""real3_abs"", (Real3 (*)(const Real3&)) abs); + m.def(""real3_dot_product"", (Real3::value_type (*)(const Real3&, const Real3&)) &dot_product); + m.def(""cross_product"", (Real3 (*)(const Real3&, const Real3&)) &cross_product); + + m.def(""real3_length_sq"", (Real3::value_type (*)(const Real3&)) &length_sq); + m.def(""real3_length"", (Real3::value_type (*)(const Real3&)) &length); + + m.def(""length_sq"", (Real3::value_type (*)(const Real3&)) &length_sq); + m.def(""length"", (Real3::value_type (*)(const Real3&)) &length); + m.def(""dot_product"", (Real3::value_type (*)(const Real3&, const Real3&)) &dot_product); + + m.def(""ones"", &ones); + m.def(""unitx"", &unitx); + m.def(""unity"", &unity); + m.def(""unitz"", &unitz); +} + +static inline +void define_integer3(py::module& m) +{ + py::class_(m, ""Integer3"") + .def(py::init(), + py::arg(""col""), py::arg(""row""), py::arg(""layer"")) + .def_readwrite(""col"", &Integer3::col) + .def_readwrite(""row"", &Integer3::row) + .def_readwrite(""layer"", &Integer3::layer) + .def(py::self == py::self) + .def(py::self += py::self) + .def(py::self + py::self) + .def(py::self -= py::self) + .def(py::self - py::self) + .def(py::self *= Integer3::value_type()) + .def(""__mul__"", [](const Integer3& x, Integer3::value_type y) { return multiply(x, y); }, py::is_operator()) + .def(""__rmul__"", [](const Integer3& x, Integer3::value_type y) { return multiply(x, y); }, py::is_operator()) + .def(""__setitem__"", [](Integer3& x, Integer3::size_type i, Integer3::value_type value) { x[i] = value; }, py::is_operator()) + .def(""__getitem__"", [](const Integer3& x, Integer3::size_type i) { return x[i]; }, py::is_operator()) + .def(""__abs__"", [](const Integer3& x) { return abs(x); }, py::is_operator()) + .def(py::pickle( + [](const Integer3& x) + { + return py::make_tuple(x.col, x.row, x.layer); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return Integer3( + t[0].cast(), + t[1].cast(), + t[2].cast()); + } + )); + + m.def(""integer3_add"", [](const Integer3& x, const Integer3& y) { return x + y; }); + m.def(""integer3_subtract"", [](const Integer3& x, const Integer3& y) { return x - y; }); + m.def(""integer3_multiply"", (Integer3 (*)(const Integer3&, const Integer3::value_type&)) &multiply); + + m.def(""integer3_length_sq"", (Integer3::value_type (*)(const Integer3&)) &length_sq); + m.def(""integer3_length"", (Real (*)(const Integer3&)) &length); + + m.def(""integer3_dot_product"", (Integer3::value_type (*)(const Integer3&, const Integer3&)) &dot_product); + m.def(""integer3_abs"", (Integer3 (*)(const Integer3&)) &abs); + + m.def(""length_sq"", (Integer3::value_type (*)(const Integer3&)) &length_sq); + m.def(""length"", (Real (*)(const Integer3&)) &length); + m.def(""dot_product"", (Integer3::value_type (*)(const Integer3&, const Integer3&)) &dot_product); +} + +template +static inline +py::class_> define_quantity(py::module& m, const std::string& name) +{ + using Q = Quantity; + py::class_ quantity(m, name.c_str()); + quantity + .def(py::init(), + py::arg(""magnitude""), + py::arg(""units"") = """") + .def_readwrite(""magnitude"", &Q::magnitude) + .def_readwrite(""units"", &Q::units) + .def(py::self == py::self) + .def(py::pickle( + [](const Q& q) + { + return py::make_tuple(q.magnitude, q.units); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return Q( + t[0].cast(), + t[1].cast()); + } + )); + return quantity; +} + +template +static inline +void set_attribute_as(Attribute& attr, const std::pair& key_value) +{ + try + { + const T value(key_value.second.cast()); + attr.set(key_value.first, value); + } + catch (py::cast_error e) + { + ; // do nothing + } +} + +static inline +void define_attribute(py::module& m) +{ + py::class_(m, ""Attriubte"") + .def(py::pickle( + [](const Attribute& self) + { + return py::make_tuple(self.values()); + }, + [](py::tuple t) + { + if (t.size() != 1) + { + throw std::runtime_error(""Invalid state""); + } + + Attribute attr; + for (const auto& key_value : t[0].cast>>()) + { + set_attribute_as(attr, key_value); + set_attribute_as>(attr, key_value); + set_attribute_as>(attr, key_value); + set_attribute_as(attr, key_value); + } + return attr; + } + )); +} + +static inline +void define_species(py::module& m) +{ + py::class_(m, ""UnitSpecies"") + .def(py::init<>()) + .def(py::init(), py::arg(""name"")) + .def(""name"", &UnitSpecies::name) + .def(""set_name"", &UnitSpecies::set_name) + .def(""deserialize"", &UnitSpecies::deserialize) + .def(""serial"", &UnitSpecies::serial) + .def(""clear"", &UnitSpecies::clear) + .def(""add_site"", &UnitSpecies::add_site) + // .def(""num_sites"", &UnitSpecies::num_sites) + .def(""has_site"", &UnitSpecies::has_site) + .def(""get_site"", &UnitSpecies::get_site) + .def(""sites"", &UnitSpecies::sites) + .def(py::self == py::self) + .def(""__hash__"", + [](const UnitSpecies& self) + { + return std::hash()(self); + } + ) + .def(py::pickle( + [](const UnitSpecies& self) + { + return py::make_tuple(self.serial()); + }, + [](py::tuple t) + { + if (t.size() != 1) + throw std::runtime_error(""Invalid state""); + auto usp = UnitSpecies(); + usp.deserialize(t[0].cast()); + return usp; + } + )); + py::class_(m, ""Species"") + .def(py::init<>()) + .def(py::init(), py::arg(""serial"")) + .def(py::init(), + py::arg(""serial""), py::arg(""radius""), py::arg(""D""), + py::arg(""location"") = """", + py::arg(""dimension"") = 0) + .def(py::init&, const Quantity&, const std::string, const Integer&>(), + py::arg(""serial""), py::arg(""radius""), py::arg(""D""), + py::arg(""location"") = """", + py::arg(""dimension"") = 0) + .def(""serial"", &Species::serial) + .def(""get_attribute"", &Species::get_attribute) + .def(""set_attribute"", &Species::set_attribute) + .def(""set_attribute"", &Species::set_attribute) + .def(""set_attribute"", &Species::set_attribute) //XXX: This must be former than Integer's + .def(""set_attribute"", &Species::set_attribute) + .def(""set_attribute"", &Species::set_attribute) + .def(""set_attribute"", &Species::set_attribute>) + .def(""set_attribute"", &Species::set_attribute>) + .def(""remove_attribute"", &Species::remove_attribute) + .def(""has_attribute"", &Species::has_attribute) + .def(""list_attributes"", &Species::list_attributes) + .def(""add_unit"", &Species::add_unit) + .def(""count"", &Species::count) + .def(""units"", &Species::units) + .def(""D"", &Species::D) + .def(""radius"", &Species::radius) + .def(""location"", &Species::location) + .def(""dimension"", &Species::dimension) + .def(py::self == py::self) + .def(py::self < py::self) + .def(py::self > py::self) + .def(""__hash__"", + [](const Species& self) + { + return std::hash()(self); + } + ) + .def(py::pickle( + [](const Species& species) + { + return py::make_tuple(species.serial(), species.attributes()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + Species species(t[0].cast()); + species.set_attributes(t[1].cast()); + return species; + } + )); + + m.def(""count_species_matches"", &count_species_matches); + m.def(""format_species"", &format_species); +} + +static inline +void define_particle(py::module& m) +{ + py::class_(m, ""ParticleID"") + .def(py::init<>()) + .def(py::init(), py::arg(""value"")) + .def(""lot"", (const ParticleID::lot_type& (ParticleID::*)() const) &ParticleID::lot) + .def(""serial"", (const ParticleID::serial_type& (ParticleID::*)() const) &ParticleID::serial) + .def(py::pickle( + [](const ParticleID& pid) + { + return py::make_tuple(pid.lot(), pid.serial()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return ParticleID(std::make_pair( + t[0].cast(), + t[1].cast() + )); + } + )); + py::class_(m, ""Particle"") + .def(py::init(), + py::arg(""sp""), py::arg(""pos""), py::arg(""radius""), py::arg(""D"")) + .def(""position"", (const Real3& (Particle::*)() const) &Particle::position) + .def(""radius"", (const Real& (Particle::*)() const) &Particle::radius) + .def(""D"", (const Real& (Particle::*)() const) &Particle::D) + .def(""species"", (const Species& (Particle::*)() const) &Particle::species) + .def(py::pickle( + [](const Particle& self) + { + return py::make_tuple(self.species(), self.position(), self.radius(), self.D()); + }, + [](py::tuple t) + { + if (t.size() != 4) + throw std::runtime_error(""Invalid state""); + return Particle( + t[0].cast(), + t[1].cast(), + t[2].cast(), + t[3].cast() + ); + } + )); +} + +static inline +void define_rng(py::module& m) +{ + py::class_, + std::shared_ptr>(m, ""RandomNumberGenerator"") + .def(""uniform"", &RandomNumberGenerator::uniform) + .def(""uniform"", &RandomNumberGenerator::uniform) + .def(""uniform_int"", &RandomNumberGenerator::uniform_int) + .def(""gaussian"", &RandomNumberGenerator::gaussian, + py::arg(""sigma""), py::arg(""mean"") = 0.0) + .def(""binomial"", &RandomNumberGenerator::binomial) + .def(""seed"", (void (RandomNumberGenerator::*)()) &RandomNumberGenerator::seed) + .def(""seed"", (void (RandomNumberGenerator::*)(Integer)) &RandomNumberGenerator::seed) + .def(""save"", (void (RandomNumberGenerator::*)(const std::string&) const) &RandomNumberGenerator::save) + .def(""load"", (void (RandomNumberGenerator::*)(const std::string&)) &RandomNumberGenerator::load); + + py::class_, + std::shared_ptr>(m, ""GSLRandomNumberGenerator"") + .def(py::init<>()) + .def(py::init(), py::arg(""seed"")) + .def(py::init(), py::arg(""filename"")); +} + +static inline +void define_reaction_rule(py::module& m) +{ + using Reactants = ReactionRule::reactant_container_type; + using Products = ReactionRule::product_container_type; + + py::class_ reaction_rule(m, ""ReactionRule""); + reaction_rule + .def(py::init<>()) + .def(py::init(), + py::arg(""reactants""), py::arg(""products"")) + .def(py::init(), + py::arg(""reactants""), py::arg(""products""), py::arg(""k"")) + .def(py::init&>(), + py::arg(""reactants""), py::arg(""products""), py::arg(""k"")) + .def(""k"", &ReactionRule::k) + .def(""set_k"", (void (ReactionRule::*)(const Real&)) &ReactionRule::set_k) + .def(""set_k"", (void (ReactionRule::*)(const Quantity&)) &ReactionRule::set_k) + .def(""get_k"", &ReactionRule::get_k) + .def(""reactants"", &ReactionRule::reactants) + .def(""products"", &ReactionRule::products) + .def(""add_reactant"", &ReactionRule::add_reactant) + .def(""add_product"", &ReactionRule::add_product) + .def(""as_string"", &ReactionRule::as_string) + .def(""policy"", &ReactionRule::policy) + .def(""set_policy"", &ReactionRule::set_policy) + .def(""count"", &ReactionRule::count) + .def(""generate"", &ReactionRule::generate) + .def(""set_descriptor"", &ReactionRule::set_descriptor) + .def(""get_descriptor"", &ReactionRule::get_descriptor) + .def(""has_descriptor"", &ReactionRule::has_descriptor) + .def(""reset_descriptor"", &ReactionRule::reset_descriptor) + .def(""get_attribute"", &ReactionRule::get_attribute) + .def(""set_attribute"", &ReactionRule::set_attribute) + .def(""set_attribute"", &ReactionRule::set_attribute) + .def(""set_attribute"", &ReactionRule::set_attribute) //XXX: This must be former than Integer's + .def(""set_attribute"", &ReactionRule::set_attribute) + .def(""set_attribute"", &ReactionRule::set_attribute) + .def(""set_attribute"", &ReactionRule::set_attribute>) + .def(""set_attribute"", &ReactionRule::set_attribute>) + .def(""remove_attribute"", &ReactionRule::remove_attribute) + .def(""has_attribute"", &ReactionRule::has_attribute) + .def(""list_attributes"", &ReactionRule::list_attributes) + .def(py::self == py::self) + .def(py::self < py::self) + .def(py::pickle( + [](const ReactionRule& self) + { + return py::make_tuple(self.reactants(), self.products(), self.get_k(), self.get_descriptor(), self.policy(), self.attributes()); + }, + [](py::tuple t) + { + if (t.size() != 6) + throw std::runtime_error(""Invalid state""); + ReactionRule rr( + t[0].cast(), + t[1].cast(), + t[2].cast >() + ); + rr.set_descriptor(t[3].cast>()); + rr.set_policy(t[4].cast()); + rr.set_attributes(t[5].cast()); + return rr; + } + )); + + py::enum_(reaction_rule, ""ReactionRulePolicy"") + .value(""STRICT"", ReactionRule::policy_type::POLICY_STRICT) + .value(""IMPLICIT"", ReactionRule::policy_type::POLICY_IMPLICIT) + .value(""DESTROY"", ReactionRule::policy_type::POLICY_DESTROY) + .export_values() + .def(py::self | py::self); + + m.def(""create_degradation_reaction_rule"", &create_degradation_reaction_rule); + m.def(""create_synthesis_reaction_rule"", &create_synthesis_reaction_rule); + m.def(""create_unimolecular_reaction_rule"", &create_unimolecular_reaction_rule); + m.def(""create_binding_reaction_rule"", &create_binding_reaction_rule); + m.def(""create_unbinding_reaction_rule"", &create_unbinding_reaction_rule); +} + +static inline +void define_model(py::module& m) +{ + py::class_, std::shared_ptr>(m, ""Model"") + .def(""query_reaction_rules"", (std::vector (Model::*)(const Species&) const) + &Model::query_reaction_rules) + .def(""query_reaction_rules"", (std::vector (Model::*)(const Species&, const Species&) const) + &Model::query_reaction_rules) + .def(""update_species_attribute"", &Model::update_species_attribute) + .def(""add_species_attribute"", &Model::add_species_attribute, py::arg(""sp""), py::arg(""proceed"") = false) + .def(""has_species_attribute"", &Model::has_species_attribute) + .def(""remove_species_attribute"", &Model::remove_species_attribute) + .def(""apply_species_attributes"", &Model::apply_species_attributes) + .def(""add_reaction_rule"", &Model::add_reaction_rule) + .def(""remove_reaction_rule"", &Model::remove_reaction_rule) + .def(""has_reaction_rule"", &Model::has_reaction_rule) + .def(""reaction_rules"", &Model::reaction_rules) + .def(""species_attributes"", &Model::species_attributes) + .def(""species_attributes_proceed"", &Model::species_attributes_proceed) + .def(""num_reaction_rules"", &Model::num_reaction_rules) + .def(""is_static"", &Model::is_static) + .def(""expand"", (std::shared_ptr (Model::*)( + const std::vector&, const Integer, const std::map&) const) &Model::expand) + .def(""expand"", (std::shared_ptr (Model::*)(const std::vector&, const Integer) const) &Model::expand) + .def(""expand"", (std::shared_ptr (Model::*)(const std::vector&) const) &Model::expand) + .def(""list_species"", &Model::list_species) + .def(""add_species_attributes"", (void (Model::*)(const std::vector&)) &Model::add_species_attributes) + .def(""add_species_attributes"", (void (Model::*)(const std::vector >&)) &Model::add_species_attributes) + .def(""add_reaction_rules"", &Model::add_reaction_rules); + + py::class_, + std::shared_ptr>(m, ""NetworkModel"") + .def(py::init<>()) + .def(py::pickle( + [](const NetworkModel& self) + { + return py::make_tuple( + self.species_attributes(), + self.species_attributes_proceed(), + self.reaction_rules()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + NetworkModel model; + model.add_species_attributes( + t[0].cast(), + t[1].cast >()); + model.add_reaction_rules(t[2].cast()); + return model; + } + )); + + py::class_, + std::shared_ptr>(m, ""NetfreeModel"") + .def(py::init<>()) + .def(""set_effective"", &NetfreeModel::set_effective) + .def(""effective"", &NetfreeModel::effective) + .def(py::pickle( + [](const NetfreeModel& self) + { + return py::make_tuple( + self.species_attributes(), + self.species_attributes_proceed(), + self.reaction_rules()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + NetfreeModel model; + model.add_species_attributes( + t[0].cast(), + t[1].cast >()); + model.add_reaction_rules(t[2].cast()); + return model; + } + )); +} + +static inline +void define_world_interface(py::module& m) +{ + py::class_, std::shared_ptr>(m, ""WorldInterface"") + .def(""t"", &WorldInterface::t) + .def(""set_t"", &WorldInterface::set_t) + .def(""save"", &WorldInterface::save) + .def(""load"", &WorldInterface::load) + .def(""volume"", &WorldInterface::volume) + .def(""has_species"", &WorldInterface::has_species) + .def(""list_species"", &WorldInterface::list_species) + .def(""num_molecules"", &WorldInterface::num_molecules) + .def(""num_molecules_exact"", &WorldInterface::num_molecules_exact) + .def(""get_value"", &WorldInterface::get_value) + .def(""get_value_exact"", &WorldInterface::get_value_exact) + .def(""edge_lengths"", &WorldInterface::edge_lengths) + .def(""num_particles"", + (Integer (WorldInterface::*)() const) &WorldInterface::num_particles) + .def(""num_particles"", + (Integer (WorldInterface::*)(const Species&) const) &WorldInterface::num_particles) + .def(""num_particles_exact"", &WorldInterface::num_particles_exact) + .def(""has_particle"", &WorldInterface::has_particle) + .def(""get_particle"", &WorldInterface::get_particle) + .def(""list_particles"", + (std::vector> (WorldInterface::*)() const) + &WorldInterface::list_particles) + .def(""list_particles"", + (std::vector> (WorldInterface::*)(const Species&) const) + &WorldInterface::list_particles) + .def(""list_particles_exact"", &WorldInterface::list_particles_exact) + ; +} + +static inline +void define_reaction_rule_descriptor(py::module& m) +{ + py::class_, + std::shared_ptr>(m, ""ReactionRuleDescriptor"") + .def(""propensity"", &ReactionRuleDescriptor::propensity) + .def(""reactant_coefficients"", &ReactionRuleDescriptor::reactant_coefficients) + .def(""product_coefficients"", &ReactionRuleDescriptor::product_coefficients) + .def(""set_reactant_coefficient"", &ReactionRuleDescriptor::set_reactant_coefficient) + .def(""set_product_coefficient"", &ReactionRuleDescriptor::set_product_coefficient) + .def(""set_reactant_coefficients"", &ReactionRuleDescriptor::set_reactant_coefficients) + .def(""set_product_coefficients"", &ReactionRuleDescriptor::set_product_coefficients); + + py::class_, + std::shared_ptr>(m, ""ReactionRuleDescriptorMassAction"") + .def(py::init(), py::arg(""k"")) + .def(py::init&>(), py::arg(""k"")) + .def(""k"", &ReactionRuleDescriptorMassAction::k) + .def(""get_k"", &ReactionRuleDescriptorMassAction::get_k) + .def(""set_k"", (void (ReactionRuleDescriptorMassAction::*)(const Real)) &ReactionRuleDescriptorMassAction::set_k) + .def(""set_k"", (void (ReactionRuleDescriptorMassAction::*)(const Quantity&)) &ReactionRuleDescriptorMassAction::set_k) + .def(py::pickle( + [](const ReactionRuleDescriptorMassAction& self) + { + return py::make_tuple(self.reactant_coefficients(), self.product_coefficients(), self.get_k()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + ReactionRuleDescriptorMassAction ret(t[2].cast>()); + ret.set_reactant_coefficients(t[0].cast()); + ret.set_product_coefficients(t[1].cast()); + return ret; + } + )); + + py::class_, + std::shared_ptr>(m, ""ReactionRuleDescriptorPyfunc"") + .def(py::init(), + py::arg(""pyfunc""), py::arg(""name"")) + .def(""get"", &ReactionRuleDescriptorPyfunc::get) + .def(""set_name"", &ReactionRuleDescriptorPyfunc::set_name) + .def(""as_string"", &ReactionRuleDescriptorPyfunc::as_string) + .def(py::pickle( + [](const ReactionRuleDescriptorPyfunc& self) + { + return py::make_tuple(self.get(), self.as_string(), self.reactant_coefficients(), self.product_coefficients()); + }, + [](py::tuple t) + { + if (t.size() != 4) + throw std::runtime_error(""Invalid state""); + return ReactionRuleDescriptorPyfunc( + t[0].cast(), + t[1].cast(), + t[2].cast(), + t[3].cast() + ); + } + )); +} + +static inline +void define_observers(py::module& m) +{ + py::class_(m, ""TimingEvent"") + .def(py::pickle( + [](const TimingEvent& obj) { + return py::make_tuple(obj.times, obj.num_steps, obj.count); + }, + [](py::tuple state) { + if (state.size() != 3) + throw std::runtime_error(""Invalid state!""); + auto obj = TimingEvent(state[0].cast >()); + obj.num_steps = state[1].cast(); + obj.count = state[2].cast(); + return obj; + } + )); + + py::class_(m, ""FixedIntervalEvent"") + .def(py::pickle( + [](const FixedIntervalEvent& obj) { + return py::make_tuple(obj.t0, obj.dt, obj.num_steps, obj.count); + }, + [](py::tuple state) { + if (state.size() != 4) + throw std::runtime_error(""Invalid state!""); + auto obj = FixedIntervalEvent(state[1].cast()); + obj.t0 = state[0].cast(); + obj.num_steps = state[2].cast(); + obj.count = state[3].cast(); + return obj; + } + )); + + py::class_(m, ""NumberLogger"") + .def(py::pickle( + [](const NumberLogger& obj) { + return py::make_tuple(obj.targets, obj.data, obj.all_species); + }, + [](py::tuple state) { + if (state.size() != 3) + throw std::runtime_error(""Invalid state!""); + auto obj = NumberLogger(); + obj.data = state[1].cast > >(); + obj.targets = state[0].cast >(); + obj.all_species = state[2].cast(); + return obj; + } + )); + + py::class_, std::shared_ptr>(m, ""Observer"") + .def(""next_time"", &Observer::next_time) + .def(""reset"", &Observer::reset) + .def(""num_steps"", &Observer::num_steps) + .def(""fire"", &Observer::fire); + + py::class_, + std::shared_ptr>(m, ""FixedIntervalNumberObserver"") + .def(py::init(), py::arg(""dt"")) + .def(py::init&>(), + py::arg(""dt""), py::arg(""species"")) + .def(""dt"", &FixedIntervalNumberObserver::dt) + .def(""t0"", &FixedIntervalNumberObserver::t0) + .def(""count"", &FixedIntervalNumberObserver::count) + .def(""data"", &FixedIntervalNumberObserver::data) + .def(""targets"", &FixedIntervalNumberObserver::targets) + .def(""save"", &FixedIntervalNumberObserver::save) + .def(py::pickle( + [](const FixedIntervalNumberObserver& obj) { + return py::make_tuple(obj.logger(), obj.num_steps(), obj.dt(), obj.t0(), obj.count()); + }, + [](py::tuple state) { + if (state.size() != 5) + throw std::runtime_error(""Invalid state!""); + auto obj = FixedIntervalNumberObserver( + state[2].cast(), state[3].cast(), state[4].cast()); + obj.set_logger(state[0].cast()); + obj.set_num_steps(state[1].cast()); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""NumberObserver"") + .def(py::init<>()) + .def(py::init&>(), py::arg(""species"")) + .def(""data"", &NumberObserver::data) + .def(""targets"", &NumberObserver::targets) + .def(""save"", &NumberObserver::save) + .def(py::pickle( + [](const NumberObserver& obj) { + return py::make_tuple(obj.logger(), obj.num_steps()); + }, + [](py::tuple state) { + if (state.size() != 2) + throw std::runtime_error(""Invalid state!""); + auto obj = NumberObserver(); + obj.set_logger(state[0].cast()); + obj.set_num_steps(state[1].cast()); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""TimingNumberObserver"") + .def(py::init&>(), py::arg(""t"")) + .def(py::init&, const std::vector&>(), + py::arg(""t""), py::arg(""species"")) + .def(""data"", &TimingNumberObserver::data) + .def(""targets"", &TimingNumberObserver::targets) + .def(""save"", &TimingNumberObserver::save) + .def(py::pickle( + [](const TimingNumberObserver& obj) { + return py::make_tuple(obj.logger(), obj.timings(), obj.num_steps(), obj.count()); + }, + [](py::tuple state) { + if (state.size() != 4) + throw std::runtime_error(""Invalid state!""); + auto obj = TimingNumberObserver( + state[1].cast >(), + state[2].cast(), + state[3].cast()); + obj.set_logger(state[0].cast()); + // obj.set_num_steps(state[4].cast()); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""FixedIntervalHDF5Observer"") + .def(py::init(), + py::arg(""dt""), py::arg(""filename"")) + .def(""prefix"", &FixedIntervalHDF5Observer::prefix) + .def(""filename"", (const std::string (FixedIntervalHDF5Observer::*)() const) &FixedIntervalHDF5Observer::filename) + .def(""filename"", (const std::string (FixedIntervalHDF5Observer::*)(const Integer) const) &FixedIntervalHDF5Observer::filename) + .def(py::pickle( + [](const FixedIntervalHDF5Observer& obj) { + return py::make_tuple(obj.dt(), obj.t0(), obj.count(), obj.prefix(), obj.num_steps()); + }, + [](py::tuple state) { + if (state.size() != 5) + throw std::runtime_error(""Invalid state!""); + auto obj = FixedIntervalHDF5Observer( + state[0].cast(), + state[1].cast(), + state[2].cast(), + state[3].cast()); + obj.set_num_steps(state[4].cast()); + return obj; + } + )); + + py::class_(m, ""PositionLogger"") + .def(py::pickle( + [](const PositionLogger& obj) { + return py::make_tuple(obj.species, obj.header, obj.formatter, obj.serials); + }, + [](py::tuple state) { + if (state.size() != 4) + throw std::runtime_error(""Invalid state!""); + auto obj = PositionLogger(); + obj.species = state[0].cast >(); + obj.header = state[1].cast(); + obj.formatter = state[2].cast(); + obj.serials = state[3].cast(); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""FixedIntervalCSVObserver"") + .def(py::init(), + py::arg(""dt""), py::arg(""filename"")) + .def(py::init&>(), + py::arg(""dt""), py::arg(""filename""), py::arg(""species"")) + .def(""log"", &FixedIntervalCSVObserver::log) + .def(""prefix"", &FixedIntervalCSVObserver::prefix) + .def(""filename"", (const std::string (FixedIntervalCSVObserver::*)() const) &FixedIntervalCSVObserver::filename) + .def(""filename"", (const std::string (FixedIntervalCSVObserver::*)(const Integer) const) &FixedIntervalCSVObserver::filename) + .def(""dt"", &FixedIntervalCSVObserver::dt) + .def(""t0"", &FixedIntervalCSVObserver::t0) + .def(""count"", &FixedIntervalCSVObserver::count) + .def(""set_header"", &FixedIntervalCSVObserver::set_header) + .def(""set_formatter"", &FixedIntervalCSVObserver::set_formatter) + .def(py::pickle( + [](const FixedIntervalCSVObserver& obj) { + return py::make_tuple(obj.dt(), obj.prefix(), obj.t0(), obj.count(), obj.num_steps(), obj.logger()); + }, + [](py::tuple state) { + if (state.size() != 6) + throw std::runtime_error(""Invalid state!""); + auto obj = FixedIntervalCSVObserver( + state[0].cast(), + state[1].cast(), + state[2].cast(), + state[3].cast()); + obj.set_num_steps(state[4].cast()); + obj.set_logger(state[5].cast()); + return obj; + } + )); + + py::class_, std::shared_ptr>(m, ""CSVObserver"") + .def(py::init(), py::arg(""filename"")) + .def(py::init&>(), + py::arg(""filename""), py::arg(""species"")) + .def(""log"", &CSVObserver::log) + .def(""filename"", (const std::string (CSVObserver::*)() const) &CSVObserver::filename) + .def(""filename"", (const std::string (CSVObserver::*)(const Integer) const) &CSVObserver::filename) + .def(""set_header"", &CSVObserver::set_header) + .def(""set_formatter"", &CSVObserver::set_formatter) + .def(py::pickle( + [](const CSVObserver& obj) { + return py::make_tuple(obj.prefix(), obj.num_steps(), obj.logger()); + }, + [](py::tuple state) { + if (state.size() != 3) + throw std::runtime_error(""Invalid state!""); + auto obj = CSVObserver( + state[0].cast()); + obj.set_num_steps(state[1].cast()); + obj.set_logger(state[2].cast()); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""FixedIntervalTrajectoryObserver"") + .def(py::init&, const bool, const Real>(), + py::arg(""dt""), py::arg(""pids""), + py::arg(""resolve_boundary"") = FixedIntervalTrajectoryObserver::default_resolve_boundary(), + py::arg(""subdt"") = FixedIntervalTrajectoryObserver::default_subdt()) + .def(py::init(), + py::arg(""dt""), + py::arg(""resolve_boundary"") = FixedIntervalTrajectoryObserver::default_resolve_boundary(), + py::arg(""subdt"") = FixedIntervalTrajectoryObserver::default_subdt()) + .def(""data"", &FixedIntervalTrajectoryObserver::data) + .def(""num_tracers"", &FixedIntervalTrajectoryObserver::num_tracers) + .def(""t"", &FixedIntervalTrajectoryObserver::t) + .def(py::pickle( + [](const FixedIntervalTrajectoryObserver& obj) { + return py::make_tuple( + obj.pids(), + obj.resolve_boundary(), + obj.prev_positions(), + obj.data(), + obj.strides(), + obj.t(), + obj.event(), + obj.subevent()); + }, + [](py::tuple state) { + if (state.size() != 8) + throw std::runtime_error(""Invalid state!""); + const auto event = state[6].cast(); + const auto subevent = state[7].cast(); + auto obj = FixedIntervalTrajectoryObserver( + event.dt, + state[0].cast >(), + state[1].cast(), + subevent.dt, + state[2].cast >(), + state[3].cast > >(), + state[4].cast >(), + state[5].cast >()); + obj.set_event(event); + obj.set_subevent(subevent); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""TimingTrajectoryObserver"") + .def(py::init&, const std::vector&, const Real>(), + py::arg(""t""), py::arg(""pids""), + py::arg(""subdt"") = TimingTrajectoryObserver::default_subdt()) + .def(py::init&, const Real>(), + py::arg(""t""), + py::arg(""subdt"") = TimingTrajectoryObserver::default_subdt()) + .def(""data"", &TimingTrajectoryObserver::data) + .def(""num_tracers"", &TimingTrajectoryObserver::num_tracers) + .def(""t"", &TimingTrajectoryObserver::t) + .def(py::pickle( + [](const TimingTrajectoryObserver& obj) { + return py::make_tuple( + obj.pids(), + obj.prev_positions(), + obj.data(), + obj.strides(), + obj.t(), + obj.event(), + obj.subevent(), + obj.resolve_boundary()); + }, + [](py::tuple state) { + if (state.size() != 8) + throw std::runtime_error(""Invalid state!""); + const auto event = state[5].cast(); + const auto subevent = state[6].cast(); + const bool resolve_boundary = state[7].cast(); + auto obj = TimingTrajectoryObserver( + event.times, + state[0].cast >(), + (resolve_boundary ? subevent.dt : 0.0), + state[1].cast >(), + state[2].cast > >(), + state[3].cast >(), + state[4].cast >()); + obj.set_event(event); + obj.set_subevent(subevent); + return obj; + } + )); + + py::class_, std::shared_ptr>(m, ""TimeoutObserver"") + .def(py::init<>()) + .def(py::init(), py::arg(""interval"")) + .def(""interval"", &TimeoutObserver::interval) + .def(""duration"", &TimeoutObserver::duration) + .def(""accumulation"", &TimeoutObserver::accumulation) + .def(py::pickle( + [](const TimeoutObserver& obj) { + return py::make_tuple( + obj.interval(), obj.duration(), obj.accumulation(), + obj.num_steps(), obj.start_time_point()); + }, + [](py::tuple state) { + if (state.size() != 5) + throw std::runtime_error(""Invalid state!""); + auto obj = TimeoutObserver( + state[0].cast(), state[1].cast(), state[2].cast()); + obj.set_num_steps(state[3].cast()); + obj.set_start_time_point(state[4].cast()); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""FixedIntervalTrackingObserver"") + .def(py::init&, const bool&, const Real, const Real>(), + py::arg(""dt""), py::arg(""species""), + py::arg(""resolve_boundary"") = FixedIntervalTrackingObserver::default_resolve_boundary(), + py::arg(""subdt"") = FixedIntervalTrackingObserver::default_subdt(), + py::arg(""threshold"") = FixedIntervalTrackingObserver::default_threshold()) + .def(""data"", &FixedIntervalTrackingObserver::data) + .def(""num_tracers"", &FixedIntervalTrackingObserver::num_tracers) + .def(""t"", &FixedIntervalTrackingObserver::t) + .def(py::pickle( + [](const FixedIntervalTrackingObserver& obj) { + return py::make_tuple( + obj.pids(), + obj.resolve_boundary(), + obj.prev_positions(), + obj.data(), + obj.strides(), + obj.t(), + obj.event(), + obj.subevent(), + obj.species(), + obj.threshold()); + }, + [](py::tuple state) { + if (state.size() != 10) + throw std::runtime_error(""Invalid state!""); + const auto event = state[6].cast(); + const auto subevent = state[7].cast(); + auto obj = FixedIntervalTrackingObserver( + event.dt, + state[0].cast >(), + state[1].cast(), + subevent.dt, + state[2].cast >(), + state[3].cast > >(), + state[4].cast >(), + state[5].cast >(), + state[8].cast >(), + state[9].cast() + ); + obj.set_event(event); + obj.set_subevent(subevent); + return obj; + } + )); + + py::class_, + std::shared_ptr>(m, ""FixedIntervalPythonHooker"") + .def(py::init(), + py::arg(""dt""), py::arg(""pyfunc"")); +} + +static inline +void define_shape(py::module& m) +{ + py::class_, std::shared_ptr> shape(m, ""Shape""); + shape.def(""dimension"", [](const Shape& self) { return static_cast(self.dimension()); }) + .def(""is_inside"", &Shape::is_inside); + py::enum_(shape, ""dimension_kind"") + .value(""ONE"", Shape::dimension_kind::ONE) + .value(""TWO"", Shape::dimension_kind::TWO) + .value(""THREE"", Shape::dimension_kind::THREE) + .value(""UNDEF"", Shape::dimension_kind::UNDEF) + .export_values(); + + py::class_, std::shared_ptr>(m, ""Surface"") + .def(""root"", &Surface::root) + .def(py::pickle( + [](const Surface& self) + { + return py::make_tuple(self.root()); + }, + [](py::tuple t) + { + if (t.size() != 1) + throw std::runtime_error(""Invalid state""); + return Surface(t[0].cast&>()); + } + )); + + py::class_, std::shared_ptr>(m, ""Union"") + .def(py::init&, const std::shared_ptr&>(), + py::arg(""a""), py::arg(""b"")) + .def(""surface"", &Union::surface) + .def(""one"", &Union::one) + .def(""another"", &Union::another) + .def(py::pickle( + [](const Union& self) + { + return py::make_tuple(self.one(), self.another()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return Union( + t[0].cast&>(), + t[1].cast&>() + ); + } + )); + + py::class_, std::shared_ptr>(m, ""Complement"") + .def(py::init&, const std::shared_ptr&>(), + py::arg(""a""), py::arg(""b"")) + .def(""surface"", &Complement::surface) + .def(""one"", &Complement::one) + .def(""another"", &Complement::another) + .def(py::pickle( + [](const Complement& self) + { + return py::make_tuple(self.one(), self.another()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return Complement( + t[0].cast&>(), + t[1].cast&>() + ); + } + )); + + py::class_, + std::shared_ptr>(m, ""AffineTransformation"") + .def(py::init<>()) + .def(py::init&>(), py::arg(""root"")) + .def(py::init&, const Real3&, const Real3&, const Real3&, const Real3&>(), + py::arg(""root""), py::arg(""first""), py::arg(""second""), py::arg(""third""), py::arg(""shift"")) + .def(""translate"", &AffineTransformation::translate) + .def(""rescale"", &AffineTransformation::rescale) + .def(""xroll"", &AffineTransformation::xroll) + .def(""yroll"", &AffineTransformation::yroll) + .def(""zroll"", &AffineTransformation::zroll) + .def(""surface"", &AffineTransformation::surface) + .def(""root"", &AffineTransformation::root) + .def(""first"", &AffineTransformation::first) + .def(""second"", &AffineTransformation::second) + .def(""third"", &AffineTransformation::third) + .def(""shift"", &AffineTransformation::shift) + .def(py::pickle( + [](const AffineTransformation& self) + { + return py::make_tuple(self.root(), self.first(), self.second(), self.third(), self.shift()); + }, + [](py::tuple t) + { + if (t.size() != 5) + throw std::runtime_error(""Invalid state""); + return AffineTransformation( + t[0].cast&>(), + t[1].cast(), + t[2].cast(), + t[3].cast(), + t[4].cast() + ); + } + )); + + py::class_, std::shared_ptr>(m, ""Sphere"") + .def(py::init(), py::arg(""center""), py::arg(""radius"")) + .def(""distance"", &Sphere::distance) + .def(""surface"", &Sphere::surface) + .def(""center"", &Sphere::center) + .def(""radius"", &Sphere::radius) + .def(py::pickle( + [](const Sphere& self) + { + return py::make_tuple(self.center(), self.radius()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return Sphere(t[0].cast(), t[1].cast()); + } + )); + + py::class_, + std::shared_ptr>(m, ""SphericalSurface"") + .def(py::init(), py::arg(""center""), py::arg(""radius"")) + .def(""distance"", &SphericalSurface::distance) + .def(""inside"", &SphericalSurface::inside) + .def(""center"", &SphericalSurface::center) + .def(""radius"", &SphericalSurface::radius) + .def(py::pickle( + [](const SphericalSurface& self) + { + return py::make_tuple(self.center(), self.radius()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return SphericalSurface(t[0].cast(), t[1].cast()); + } + )); + + py::class_, std::shared_ptr>(m, ""Cylinder"") + .def(py::init(), + py::arg(""center""), py::arg(""radius""), py::arg(""axis""), py::arg(""half_height"")) + .def(""distance"", &Cylinder::distance) + .def(""surface"", &Cylinder::surface) + .def(""center"", &Cylinder::center) + .def(""axis"", &Cylinder::axis) + .def(""half_height"", &Cylinder::half_height) + .def(py::pickle( + [](const Cylinder& self) + { + return py::make_tuple(self.center(), self.radius(), self.axis(), self.half_height()); + }, + [](py::tuple t) + { + if (t.size() != 4) + throw std::runtime_error(""Invalid state""); + return Cylinder( + t[0].cast(), + t[1].cast(), + t[2].cast(), + t[3].cast() + ); + } + )); + + py::class_, + std::shared_ptr>(m, ""CylindricalSurface"") + .def(py::init(), + py::arg(""center""), py::arg(""radius""), py::arg(""axis""), py::arg(""half_height"")) + .def(""distance"", &CylindricalSurface::distance) + .def(""inside"", &CylindricalSurface::inside) + .def(""center"", &CylindricalSurface::center) + .def(""radius"", &CylindricalSurface::radius) + .def(""axis"", &CylindricalSurface::axis) + .def(""half_height"", &CylindricalSurface::half_height) + .def(py::pickle( + [](const CylindricalSurface& self) + { + return py::make_tuple(self.center(), self.radius(), self.axis(), self.half_height()); + }, + [](py::tuple t) + { + if (t.size() != 4) + throw std::runtime_error(""Invalid state""); + return CylindricalSurface( + t[0].cast(), + t[1].cast(), + t[2].cast(), + t[3].cast() + ); + } + )); + + py::class_, + std::shared_ptr>(m, ""PlanarSurface"") + .def(py::init(), + py::arg(""origin""), py::arg(""e0""), py::arg(""e1"")) + .def(""origin"", &PlanarSurface::origin) + .def(""e0"", &PlanarSurface::e0) + .def(""e1"", &PlanarSurface::e1) + .def(""normal"", &PlanarSurface::normal) + .def(py::pickle( + [](const PlanarSurface& self) + { + return py::make_tuple(self.origin(), self.e0(), self.e1()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return PlanarSurface( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); + + py::class_, std::shared_ptr>(m, ""Rod"") + .def(py::init(), + py::arg(""length""), py::arg(""radius""), + py::arg(""origin"") = Real3()) + .def(""distance"", &Rod::distance) + .def(""origin"", &Rod::origin) + .def(""length"", &Rod::length) + .def(""radius"", &Rod::radius) + .def(""shift"", &Rod::shift) + .def(""surface"", &Rod::surface) + .def(py::pickle( + [](const Rod& self) + { + return py::make_tuple(self.length(), self.radius(), self.origin()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return Rod( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); + + py::class_, std::shared_ptr>(m, ""RodSurface"") + .def(py::init(), + py::arg(""length""), py::arg(""radius""), + py::arg(""origin"") = Real3()) + .def(""distance"", &RodSurface::distance) + .def(""origin"", &RodSurface::origin) + .def(""length"", &RodSurface::length) + .def(""radius"", &RodSurface::radius) + .def(""shift"", &RodSurface::shift) + .def(py::pickle( + [](const RodSurface& self) + { + return py::make_tuple(self.length(), self.radius(), self.origin()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return RodSurface( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); + + py::class_, std::shared_ptr>(m, ""AABB"") + .def(py::init(), py::arg(""lower""), py::arg(""upper"")) + .def(""distance"", &AABB::distance) + .def(""upper"", (const Real3& (AABB::*)() const) &AABB::upper) + .def(""lower"", (const Real3& (AABB::*)() const) &AABB::lower) + .def(""upper"", (Real3& (AABB::*)()) &AABB::upper) + .def(""lower"", (Real3& (AABB::*)()) &AABB::lower) + .def(""surface"", &AABB::surface) + .def(py::pickle( + [](const AABB& self) + { + return py::make_tuple(self.lower(), self.upper()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return AABB( + t[0].cast(), + t[1].cast() + ); + } + )); + + py::class_, std::shared_ptr>(m, ""MeshSurface"") + .def(py::init(), py::arg(""filename""), py::arg(""edge_lengths"")) + .def(""filename"", &MeshSurface::filename) + .def(""edge_lengths"", &MeshSurface::edge_lengths) + .def(py::pickle( + [](const MeshSurface& self) + { + return py::make_tuple(self.filename(), self.edge_lengths()); + }, + [](py::tuple t) + { + if (t.size() != 2) + throw std::runtime_error(""Invalid state""); + return MeshSurface( + t[0].cast(), + t[1].cast() + ); + } + )); + + m.def(""create_x_plane"", + [](Real x) + { + return PlanarSurface(Real3(x, 0, 0), Real3(0, 1, 0), Real3(0, 0, 1)); + }); + + m.def(""create_y_plane"", + [](Real y) + { + return PlanarSurface(Real3(0, y, 0), Real3(1, 0, 0), Real3(0, 0, 1)); + }); + + m.def(""create_z_plane"", + [](Real z) + { + return PlanarSurface(Real3(0, 0, z), Real3(1, 0, 0), Real3(0, 1, 0)); + }); + + // ======================================================================= + // sgfrd polygon related stuff + + py::class_, std::shared_ptr>(m, ""Triangle"") + .def(py::init(), py::arg(""v1""), py::arg(""v2""), py::arg(""v3"")) + .def(""normal"", &Triangle::normal) + .def(""area"", &Triangle::area) + .def(""vertex_at"", &Triangle::vertex_at) + .def(""vertices"", &Triangle::vertices) + .def(py::pickle( + [](const Triangle& self) + { + return py::make_tuple(self.vertex_at(0), self.vertex_at(1), self.vertex_at(2)); + }, + [](py::tuple t) + { + if (t.size() != 2) + { + throw std::runtime_error(""Invalid state""); + } + return Triangle(t[0].cast(), t[1].cast(), t[2].cast()); + } + )); + + py::class_(m, ""Barycentric"") + .def(py::init()) + .def(""__setitem__"", [](Barycentric& x, Barycentric::size_type i, Barycentric::value_type value) { x.at(i) = value; }, py::is_operator()) + .def(""__getitem__"", [](const Barycentric& x, Barycentric::size_type i) { return x.at(i); }, py::is_operator()) + ; + + py::class_(m, ""FaceID""); + + py::class_, std::shared_ptr>(m, ""Polygon"") + .def(py::init(), py::arg(""edge_lengths""), py::arg(""matrix_sizes"")) + .def(py::init&>(), py::arg(""edge_lengths""), py::arg(""triangles"")) + .def(""reset"", &Polygon::reset) + .def(""triangles"", &Polygon::triangles); + + py::enum_(m, ""STLFormat"", py::arithmetic()) + .value(""Ascii"", ecell4::STLFormat::Ascii) + .value(""Binary"", ecell4::STLFormat::Binary) + .export_values(); + + m.def(""read_polygon"", &ecell4::read_polygon); + m.def(""write_polygon"", &ecell4::write_polygon); +} + + + +static inline +void define_simulator(py::module& m) +{ + py::class_, std::shared_ptr>(m, ""Simulator"") + .def(""initialize"", &Simulator::initialize) + .def(""t"", &Simulator::t) + .def(""dt"", &Simulator::dt) + .def(""set_dt"", &Simulator::set_dt) + .def(""num_steps"", &Simulator::num_steps) + .def(""step"", (void (Simulator::*)()) &Simulator::step) + .def(""step"", (bool (Simulator::*)(const Real&)) &Simulator::step) + .def(""check_reaction"", &Simulator::check_reaction) + .def(""next_time"", &Simulator::next_time); +} + +void setup_module(py::module& m) +{ + define_real3(m); + define_integer3(m); + const auto quantity_real = define_quantity(m, ""Quantity_Real""); + define_quantity(m, ""Quantity_Integer""); + m.attr(""Quantity"") = quantity_real; + define_attribute(m); + define_species(m); + define_particle(m); + define_rng(m); + define_reaction_rule(m); + define_model(m); + define_world_interface(m); + define_reaction_rule_descriptor(m); + define_observers(m); + define_shape(m); + define_simulator(m); + + m.def(""load_version_information"", (std::string (*)(const std::string&)) &extras::load_version_information); + m.def(""get_dimension_from_model"", &extras::get_dimension_from_model); + m.def(""get_stoichiometry"", &extras::get_stoichiometry); + m.def(""cbrt"", &ecell4::cbrt); + m.attr(""N_A"") = 6.022140857e+23; + m.attr(""epsilon"") = std::numeric_limits::epsilon(); + m.def(""_save_bd5"", &save_bd5); +} + +} + +} + +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/type_caster.hpp",".hpp","939","39","#ifndef ECELL4_PYTHON_API_TYPE_CASTER +#define ECELL4_PYTHON_API_TYPE_CASTER + +#include +#include +#include +#include +// #include + +PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr); + +namespace pybind11 +{ + namespace detail + { + template + struct type_caster> : variant_caster> + { + }; + + template + struct type_caster> : optional_caster> + { + }; + + template <> + struct visit_helper { + template + static auto call(Args &&... args) -> decltype(boost::apply_visitor(args...)) + { + return boost::apply_visitor(args...); + } + }; + } +} + + +#endif /* ECELL4_PYTHON_API_TYPE_CASTER */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/egfrd.cpp",".cpp","9071","215","#include ""python_api.hpp"" + +#include + +#include ""simulator.hpp"" +#include ""simulator_factory.hpp"" +#include ""world_interface.hpp"" + +namespace py = pybind11; +// using namespace ecell4::egfrd; + +namespace ecell4 +{ + +namespace python_api +{ + +static inline +void define_bd_factory(py::module& m) +{ + using namespace ::ecell4::egfrd; + using matrix_sizes_type = EGFRDWorld::matrix_sizes_type; + + py::class_ factory(m, ""BDFactory""); + factory + .def(py::init(), + py::arg(""matrix_sizes"") = BDFactory::default_matrix_sizes(), + py::arg(""bd_dt_factor"") = BDFactory::default_bd_dt_factor(), + py::arg(""dissociation_retry_moves"") = BDFactory::default_dissociation_retry_moves()) + .def(""rng"", &BDFactory::rng); + define_factory_functions(factory); +} + +static inline +void define_bd_simulator(py::module& m) +{ + using namespace ::ecell4::egfrd; + using BDSimulator = egfrd::DefaultBDSimulator; + using world_type = BDSimulator::world_type; + using model_type = BDSimulator::model_type; + + py::class_, + std::shared_ptr> simulator(m, ""BDSimulator""); + simulator + .def(py::init, Real, int>(), + py::arg(""w""), + py::arg(""bd_dt_factor"") = 1.0, + py::arg(""dissociation_retry_moves"") = 1) + .def(py::init, std::shared_ptr, Real, int>(), + py::arg(""w""), py::arg(""m""), + py::arg(""bd_dt_factor"") = 1.0, + py::arg(""dissociation_retry_moves"") = 1) + .def(""last_reactions"", &BDSimulator::last_reactions) + .def(""set_t"", &BDSimulator::set_t) + .def(""dt_factor"", &BDSimulator::dt_factor) + .def(""add_potential"", + (void (BDSimulator::*)(const Species&, const Real&)) &BDSimulator::add_potential) + .def(""add_potential"", + (void (BDSimulator::*)(const Species&, const std::shared_ptr&)) &BDSimulator::add_potential) + .def(""add_potential"", + (void (BDSimulator::*)(const Species&, const std::shared_ptr&, const Real&)) &BDSimulator::add_potential); + define_simulator_functions(simulator); +} + +static inline +void define_egfrd_factory(py::module& m) +{ + using namespace ::ecell4::egfrd; + using matrix_sizes_type = EGFRDWorld::matrix_sizes_type; + + py::class_ factory(m, ""EGFRDFactory""); + factory + .def(py::init(), + py::arg(""matrix_sizes"") = EGFRDFactory::default_matrix_sizes(), + py::arg(""bd_dt_factor"") = EGFRDFactory::default_bd_dt_factor(), + py::arg(""dissociation_retry_moves"") = EGFRDFactory::default_dissociation_retry_moves(), + py::arg(""user_max_shell_size"") = EGFRDFactory::default_user_max_shell_size()) + .def(""rng"", &EGFRDFactory::rng); + define_factory_functions(factory); + + m.attr(""Factory"") = factory; +} + +static inline +void define_egfrd_simulator(py::module& m) +{ + using world_type = ::ecell4::egfrd::DefaultEGFRDSimulator::world_type; + using model_type = ::ecell4::egfrd::DefaultEGFRDSimulator::model_type; + using length_type = ::ecell4::egfrd::DefaultEGFRDSimulator::length_type; + + py::class_<::ecell4::egfrd::DefaultEGFRDSimulator, Simulator, + PySimulator<::ecell4::egfrd::DefaultEGFRDSimulator>, + std::shared_ptr<::ecell4::egfrd::DefaultEGFRDSimulator> + > simulator(m, ""EGFRDSimulator""); + simulator + .def(py::init, Real, int, length_type>(), + py::arg(""w""), + py::arg(""bd_dt_factor"") = 1e-5, + py::arg(""dissociation_retry_moves"") = 1, + py::arg(""user_max_shell_size"") = std::numeric_limits::infinity()) + .def(py::init, std::shared_ptr, Real, int, length_type>(), + py::arg(""w""), py::arg(""m""), + py::arg(""bd_dt_factor"") = 1e-5, + py::arg(""dissociation_retry_moves"") = 1, + py::arg(""user_max_shell_size"") = std::numeric_limits::infinity()) + .def(""last_reactions"", &::ecell4::egfrd::DefaultEGFRDSimulator::last_reactions) + .def(""set_t"", &::ecell4::egfrd::DefaultEGFRDSimulator::set_t) + .def(""set_paranoiac"", &::ecell4::egfrd::DefaultEGFRDSimulator::set_paranoiac); + define_simulator_functions(simulator); + + m.attr(""Simulator"") = simulator; +} + +static inline +void define_egfrd_world(py::module& m) +{ + using namespace ::ecell4::egfrd; + using position_type = EGFRDWorld::position_type; + using matrix_sizes_type = EGFRDWorld::matrix_sizes_type; + using particle_type = EGFRDWorld::particle_type; + using particle_id_type = EGFRDWorld::particle_id_type; + using length_type = EGFRDWorld::length_type; + using rng_type = EGFRDWorld::rng_type; + + py::class_, + std::shared_ptr> world(m, ""EGFRDWorld""); + world + .def(py::init(), + py::arg(""edge_lengths"") = position_type(1.0, 1.0, 1.0), + py::arg(""matrix_sizes"") = matrix_sizes_type(3, 3, 3)) + .def(py::init&>(), + py::arg(""edge_lengths""), + py::arg(""matrix_sizes""), + py::arg(""rng"")) + .def(py::init(), py::arg(""filename"")) + .def(""new_particle"", + (std::pair, bool> (EGFRDWorld::*)(const particle_type&)) + &EGFRDWorld::new_particle) + .def(""new_particle"", + (std::pair, bool> (EGFRDWorld::*)(const Species&, const position_type&)) + &EGFRDWorld::new_particle) + .def(""matrix_sizes"", &EGFRDWorld::matrix_sizes) + .def(""set_value"", &EGFRDWorld::set_value) + .def(""update_particle"", &EGFRDWorld::update_particle) + .def(""remove_particle"", &EGFRDWorld::remove_particle) + .def(""list_particles_within_radius"", + (std::vector, length_type>> + (EGFRDWorld::*)(const position_type&, const length_type&) const) + &EGFRDWorld::list_particles_within_radius) + .def(""list_particles_within_radius"", + (std::vector, length_type>> + (EGFRDWorld::*)(const position_type&, const length_type&, const particle_id_type&) const) + &EGFRDWorld::list_particles_within_radius) + .def(""list_particles_within_radius"", + (std::vector, length_type>> + (EGFRDWorld::*)(const position_type&, const length_type&, const particle_id_type&, const particle_id_type&) const) + &EGFRDWorld::list_particles_within_radius) + .def(""apply_boundary"", &EGFRDWorld::apply_boundary) + .def(""distance"", + (length_type (EGFRDWorld::*)(const position_type&, const position_type&) const) &EGFRDWorld::distance) + .def(""add_molecules"", + (void (EGFRDWorld::*)(const Species&, const Integer&)) &EGFRDWorld::add_molecules) + .def(""add_molecules"", + (void (EGFRDWorld::*)(const Species&, const Integer&, const std::shared_ptr)) &EGFRDWorld::add_molecules) + .def(""remove_molecules"", &EGFRDWorld::remove_molecules) + .def(""bind_to"", &EGFRDWorld::bind_to) + .def(""rng"", &EGFRDWorld::rng); + + m.attr(""World"") = world; +} + +static inline +void define_reaction_info(py::module& m) +{ + using namespace ::ecell4::egfrd; + using container_type = ReactionInfo::container_type; + + py::class_(m, ""ReactionInfo"") + .def(py::init(), + py::arg(""t""), py::arg(""reactants""), py::arg(""products"")) + .def(""t"", &ReactionInfo::t) + .def(""reactants"", &ReactionInfo::reactants) + .def(""products"", &ReactionInfo::products) + .def(py::pickle( + [](const ReactionInfo& self) + { + return py::make_tuple(self.t(), self.reactants(), self.products()); + }, + [](py::tuple t) + { + if (t.size() != 3) + throw std::runtime_error(""Invalid state""); + return ReactionInfo( + t[0].cast(), + t[1].cast(), + t[2].cast() + ); + } + )); +} + +void setup_egfrd_module(py::module& m) +{ + define_bd_simulator(m); + define_bd_factory(m); + define_egfrd_factory(m); + define_egfrd_simulator(m); + define_egfrd_world(m); + define_reaction_info(m); +} + +} + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/observers.hpp",".hpp","1301","60","#ifndef ECELL4_PYTHON_API_OBSERVER_HPP +#define ECELL4_PYTHON_API_OBSERVER_HPP + +#include +#include +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + + template + class PyObserver: public Base + { + public: + using Base::Base; + + const Real next_time() const override + { + PYBIND11_OVERLOAD(const Real, Base, next_time,); + } + + void reset() override + { + PYBIND11_OVERLOAD(void, Base, reset,); + } + }; + + class FixedIntervalPythonHooker + : public FixedIntervalObserver + { + public: + using base_type = FixedIntervalObserver; + using callback_t = std::function&, bool)>; + + FixedIntervalPythonHooker(const Real& dt, callback_t callback) + : base_type(dt), callback_(callback) + { + } + + bool fire(const Simulator* sim, const std::shared_ptr& world) override + { + return callback_(world, sim->check_reaction()) && base_type::fire(sim, world); + } + + protected: + callback_t callback_; + + }; + +} + +} + +#endif /* ECELL4_PYTHON_API_OBSERVER_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/python_api/reaction_rule_descriptor.hpp",".hpp","2391","84","#ifndef ECELL4_PYTHON_API_REACTION_RULE_DESCRIPTOR_HPP +#define ECELL4_PYTHON_API_REACTION_RULE_DESCRIPTOR_HPP + +#include +#include +#include + +namespace py = pybind11; + +namespace ecell4 +{ + +namespace python_api +{ + + template + class PyReactionRuleDescriptor: public Base + { + public: + using Base::Base; + using state_container_type = ReactionRuleDescriptor::state_container_type; + + Real propensity(const state_container_type& reactants, const state_container_type& products, Real volume, Real t) const + { + PYBIND11_OVERLOAD(Real, Base, propensity, reactants, products, volume, t); + } + }; + + class ReactionRuleDescriptorPyfunc + : public ReactionRuleDescriptor + { + public: + using base_type = ReactionRuleDescriptor; + using callback_t = py::object; + + ReactionRuleDescriptorPyfunc(const callback_t& callback, const std::string& name) + : base_type(), callback_(callback), name_(name) + { + } + + ReactionRuleDescriptorPyfunc(const callback_t& callback, const std::string& name, + const coefficient_container_type& reactant_coefficients, + const coefficient_container_type& product_coefficients) + : base_type(reactant_coefficients, product_coefficients), callback_(callback), name_(name) + { + } + + Real propensity(const state_container_type& reactants, const state_container_type& products, Real volume, Real t) const override + { + return callback_(reactants, products, volume, t, reactant_coefficients(), product_coefficients()).cast(); + } + + callback_t get() const + { + return callback_; + } + + void set_name(const std::string& name) + { + name_ = name; + } + + const std::string& as_string() const + { + return name_; + } + + ReactionRuleDescriptor* clone() const + { + return new ReactionRuleDescriptorPyfunc(callback_, name_, + reactant_coefficients(), product_coefficients()); + } + + private: + callback_t callback_; + std::string name_; + }; + +} + +} + +#endif /* ECELL4_PYTHON_API_REACTION_RULE_DESCRIPTOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/GillespieFactory.hpp",".hpp","1503","76","#ifndef ECELL4_GILLESPIE_GILLESPIE_FACTORY_HPP +#define ECELL4_GILLESPIE_GILLESPIE_FACTORY_HPP + +#include +#include + +#include +#include ""GillespieWorld.hpp"" +#include ""GillespieSimulator.hpp"" + + +namespace ecell4 +{ + +namespace gillespie +{ + +class GillespieFactory: + public SimulatorFactory +{ +public: + + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef GillespieFactory this_type; + +public: + + GillespieFactory() + : base_type(), rng_() + { + ; // do nothing + } + + virtual ~GillespieFactory() + { + ; // do nothing + } + + this_type& rng(const std::shared_ptr& rng) + { + rng_ = rng; + return (*this); + } + + inline this_type* rng_ptr(const std::shared_ptr& rng) + { + return &(this->rng(rng)); //XXX: == this + } + +protected: + + virtual world_type* create_world(const Real3& edge_lengths) const + { + if (rng_) + { + return new world_type(edge_lengths, rng_); + } + else + { + return new world_type(edge_lengths); + } + } + +protected: + + std::shared_ptr rng_; +}; + +} // gillespie + +} // ecell4 + +#endif /* ECELL4_GILLESPIE_GILLESPIE_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/GillespieSimulator.cpp",".cpp","8484","323","#include ""GillespieSimulator.hpp"" +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace ecell4 +{ + +namespace gillespie +{ + +void GillespieSimulator::increment_molecules(const Species& sp) +{ + world_->add_molecules(sp, 1); + + for (boost::ptr_vector::iterator i(events_.begin()); + i != events_.end(); ++i) + { + (*i).inc(sp); + } +} + + +void GillespieSimulator::decrement_molecules(const Species& sp) +{ + world_->remove_molecules(sp, 1); + + for (boost::ptr_vector::iterator i(events_.begin()); + i != events_.end(); ++i) + { + (*i).dec(sp); + } +} + +bool GillespieSimulator::__draw_next_reaction(void) +{ + std::vector a(events_.size()); + for (unsigned int i(0); i < events_.size(); ++i) + { + // events_[i].initialize(world_.get()); + a[i] = events_[i].propensity(); + } + + const double atot(std::accumulate(a.begin(), a.end(), double(0.0))); + + if (atot == 0.0) + { + // no reaction occurs + this->dt_ = std::numeric_limits::infinity(); + return true; + } + + double dt = 0.0; + unsigned int idx = 0; + + if (atot == std::numeric_limits::infinity()) + { + std::vector selected; + for (unsigned int i(0); i < a.size(); ++i) + { + if (a[i] == std::numeric_limits::infinity()) + { + selected.push_back(i); + } + } + + dt = 0.0; + idx = selected[(selected.size() == 1 ? 0 : rng()->uniform_int(0, selected.size() - 1))]; + } + else + { + const double rnd1(rng()->uniform(0, 1)); + const double rnd2(rng()->uniform(0, atot)); + + dt = gsl_sf_log(1.0 / rnd1) / double(atot); + + double acc(0.0); + + for (idx = 0; idx < a.size(); ++idx) + { + acc += a[idx]; + if (acc >= rnd2) + { + break; + } + } + } + + next_reaction_rule_ = events_[idx].reaction_rule(); + boost::optional r = events_[idx].draw(); + this->dt_ += dt; + + if (!r) + { + return false; + } + next_reaction_ = r.get(); + return true; +} + +void GillespieSimulator::draw_next_reaction(void) +{ + if (events_.size() == 0) + { + this->dt_ = std::numeric_limits::infinity(); + return; + } + + this->dt_ = 0.0; + + while (!__draw_next_reaction()) + { + ; // pass + } +} + +void GillespieSimulator::step(void) +{ + last_reactions_.clear(); + + if (this->dt_ == std::numeric_limits::infinity()) + { + // No reaction occurs. + return; + } + + const Real t0(t()), dt0(dt()); + + // // if (dt0 == 0.0 || next_reaction_.k() <= 0.0) + // if (next_reaction_.k() <= 0.0) + // { + // // Any reactions cannot occur. + // return; + // } + + // Reaction[u] occurs. + if (!next_reaction_.has_descriptor()) + { + for (ReactionRule::reactant_container_type::const_iterator + it(next_reaction_.reactants().begin()); + it != next_reaction_.reactants().end(); ++it) + { + decrement_molecules(*it); + } + + for (ReactionRule::product_container_type::const_iterator + it(next_reaction_.products().begin()); + it != next_reaction_.products().end(); ++it) + { + increment_molecules(*it); + } + } + else + { + const std::shared_ptr& desc = next_reaction_.get_descriptor(); + assert(desc->is_available()); + + const ReactionRule::reactant_container_type& reactants(next_reaction_.reactants()); + const ReactionRuleDescriptor::coefficient_container_type& + reactant_coefficients(desc->reactant_coefficients()); + assert(reactants.size() == reactant_coefficients.size()); + for (std::size_t i = 0; i < reactants.size(); ++i) + { + assert(reactant_coefficients[i] >= 0); + for (std::size_t j = 0; j < (std::size_t)round(reactant_coefficients[i]); ++j) + { + decrement_molecules(reactants[i]); + } + } + + const ReactionRule::product_container_type& products(next_reaction_.products()); + const ReactionRuleDescriptor::coefficient_container_type& + product_coefficients(desc->product_coefficients()); + assert(products.size() == product_coefficients.size()); + for (std::size_t i = 0; i < products.size(); ++i) + { + assert(product_coefficients[i] >= 0); + for (std::size_t j = 0; j < (std::size_t)round(product_coefficients[i]); ++j) + { + increment_molecules(products[i]); + } + } + } + + this->set_t(t0 + dt0); + num_steps_++; + + last_reactions_.push_back( + std::make_pair( + next_reaction_rule_, + reaction_info_type(t(), next_reaction_.reactants(), next_reaction_.products()))); + + this->draw_next_reaction(); +} + +bool GillespieSimulator::step(const Real &upto) +{ + if (upto <= t()) + { + return false; + } + + if (upto >= next_time()) + { + step(); + return true; + } + else + { + // No reaction occurs. + // set_dt(next_time() - upto); + set_t(upto); + last_reactions_.clear(); + draw_next_reaction(); + return false; + } +} + +void GillespieSimulator::check_model() +{ + // Check if the given model is supported or not. + const Model::reaction_rule_container_type& + reaction_rules(model_->reaction_rules()); + + for (Model::reaction_rule_container_type::const_iterator + i(reaction_rules.begin()); i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + + if (rr.has_descriptor()) + { + const std::shared_ptr& desc = rr.get_descriptor(); + + if (!desc->is_available()) + { + throw NotSupported( + ""The given reaction rule descriptor is not available.""); + } + else if ((rr.reactants().size() != desc->reactant_coefficients().size()) + || (rr.products().size() != desc->product_coefficients().size())) + { + throw NotSupported( + ""Mismatch between the number of stoichiometry coefficients and of reactants.""); + } + else + { + for (ReactionRuleDescriptor::coefficient_container_type::const_iterator + it(desc->reactant_coefficients().begin()); it != desc->reactant_coefficients().end(); + it++) + { + if ((*it) < 0) + { + throw NotSupported(""A stoichiometric coefficient must be non-negative.""); + } + else if (abs((*it) - round(*it)) > 1e-10 * (*it)) + { + throw NotSupported(""A stoichiometric coefficient must be an integer.""); + } + } + } + } + else if (rr.reactants().size() > 2) + { + throw NotSupported(""No more than 2 reactants are supported.""); + } + } +} + +void GillespieSimulator::initialize(void) +{ + const Model::reaction_rule_container_type& + reaction_rules(model_->reaction_rules()); + + check_model(); + + events_.clear(); + for (Model::reaction_rule_container_type::const_iterator + i(reaction_rules.begin()); i != reaction_rules.end(); ++i) + { + const ReactionRule& rr(*i); + + if (rr.has_descriptor()) + { + events_.push_back(new DescriptorReactionRuleEvent(this, rr)); + } + else if (rr.reactants().size() == 0) + { + events_.push_back(new ZerothOrderReactionRuleEvent(this, rr)); + } + else if (rr.reactants().size() == 1) + { + events_.push_back(new FirstOrderReactionRuleEvent(this, rr)); + } + else if (rr.reactants().size() == 2) + { + events_.push_back(new SecondOrderReactionRuleEvent(this, rr)); + } + else + { + throw IllegalState(""Never get here""); + } + + events_.back().initialize(); + } + + this->draw_next_reaction(); +} + +Real GillespieSimulator::dt(void) const +{ + return this->dt_; +} + +} // gillespie + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/GillespieSimulator.hpp",".hpp","17487","619","#ifndef ECELL4_GILLESPIE_GILLESPIE_SIMULATOR_HPP +#define ECELL4_GILLESPIE_GILLESPIE_SIMULATOR_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include ""GillespieWorld.hpp"" + + +namespace ecell4 +{ + +namespace gillespie +{ + +class ReactionInfo +{ +public: + + typedef std::vector container_type; + +public: + + ReactionInfo( + const Real t, + const container_type& reactants, + const container_type& products) + : t_(t), reactants_(reactants), products_(products) + {} + + ReactionInfo( + const ReactionInfo& another) + : t_(another.t()), reactants_(another.reactants()), products_(another.products()) + {} + + Real t() const + { + return t_; + } + + const container_type& reactants() const + { + return reactants_; + } + + void add_reactant(const Species& sp) + { + reactants_.push_back(sp); + } + + const container_type& products() const + { + return products_; + } + + void add_product(const Species& sp) + { + products_.push_back(sp); + } + +protected: + + Real t_; + container_type reactants_, products_; +}; + +class GillespieSimulator + : public SimulatorBase +{ +public: + + typedef SimulatorBase base_type; + typedef ReactionInfo reaction_info_type; + +protected: + + class ReactionRuleEvent + { + public: + + ReactionRuleEvent() + : sim_(), rr_() + { + ; + } + + ReactionRuleEvent(GillespieSimulator* sim, const ReactionRule& rr) + : sim_(sim), rr_(rr) + { + ; + } + + virtual ~ReactionRuleEvent() + { + ; + } + + const ReactionRule& reaction_rule() const + { + return rr_; + } + + inline const Integer get_coef(const Species& pttrn, const Species& sp) const + { + return sim_->model()->apply(pttrn, sp); + } + + inline const std::vector generate( + const ReactionRule::reactant_container_type& reactants) const + { + return sim_->model()->apply(rr_, reactants); + } + + virtual void initialize() = 0; + virtual void inc(const Species& sp, const Integer val = +1) = 0; + virtual const Real propensity() const = 0; + + inline void dec(const Species& sp) + { + inc(sp, -1); + } + + boost::optional draw() + { + const std::pair + retval(__draw()); + if (retval.second == 0) + { + return boost::none; + } + + const std::vector reactions(generate(retval.first)); + + assert(retval.second > 0); + assert(retval.second >= static_cast(reactions.size())); + + if (reactions.size() == 0) + { + return boost::none; + } + else if (retval.second == 1) + { + // assert(possibles.size() == 1); + return reactions[0]; + } + else + { + const ReactionRule::reactant_container_type::size_type rnd2( + static_cast( + rng()->uniform_int(0, retval.second - 1))); + if (rnd2 >= reactions.size()) + { + return boost::none; + } + return reactions[rnd2]; + } + } + + protected: + + inline const std::shared_ptr& rng() const + { + return sim_->world()->rng(); + } + + inline const GillespieWorld& world() const + { + return (*sim_->world()); + } + + virtual std::pair + __draw() = 0; + + protected: + + GillespieSimulator* sim_; + ReactionRule rr_; + }; + + class ZerothOrderReactionRuleEvent + : public ReactionRuleEvent + { + public: + + typedef ReactionRuleEvent base_type; + + ZerothOrderReactionRuleEvent() + : base_type() + { + ; + } + + ZerothOrderReactionRuleEvent(GillespieSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr) + { + ; + } + + void inc(const Species& sp, const Integer val = +1) + { + ; // do nothing + } + + void initialize() + { + ; // do nothing + } + + std::pair __draw() + { + return std::make_pair(ReactionRule::reactant_container_type(), 1); + } + + const Real propensity() const + { + return rr_.k() * sim_->world()->volume(); + } + }; + + class FirstOrderReactionRuleEvent + : public ReactionRuleEvent + { + public: + + typedef ReactionRuleEvent base_type; + + FirstOrderReactionRuleEvent() + : base_type(), num_tot1_(0) + { + ; + } + + FirstOrderReactionRuleEvent(GillespieSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr), num_tot1_(0) + { + ; + } + + void inc(const Species& sp, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + const Integer coef(get_coef(reactants[0], sp)); + if (coef > 0) + { + num_tot1_ += coef * val; + } + } + + void initialize() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + num_tot1_ = 0; + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[0], *i)); + if (coef > 0) + { + num_tot1_ += coef * world().num_molecules_exact(*i); + } + } + } + + std::pair __draw() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + const Real rnd1(rng()->uniform(0.0, num_tot1_)); + + Integer num_tot(0); + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[0], *i)); + if (coef > 0) + { + num_tot += coef * world().num_molecules_exact(*i); + if (num_tot >= rnd1) + { + return std::make_pair( + ReactionRule::reactant_container_type(1, *i), coef); + } + } + } + + return std::make_pair(ReactionRule::reactant_container_type(), 0); + } + + const Real propensity() const + { + return (num_tot1_ > 0 ? num_tot1_ * rr_.k() : 0.0); + } + + protected: + + Integer num_tot1_; + }; + + class SecondOrderReactionRuleEvent: + public ReactionRuleEvent + { + public: + + typedef ReactionRuleEvent base_type; + + SecondOrderReactionRuleEvent() + : base_type(), num_tot1_(0), num_tot2_(0), num_tot12_(0) + { + ; + } + + SecondOrderReactionRuleEvent(GillespieSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr), num_tot1_(0), num_tot2_(0), num_tot12_(0) + { + ; + } + + void inc(const Species& sp, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + const Integer coef1(get_coef(reactants[0], sp)); + const Integer coef2(get_coef(reactants[1], sp)); + if (coef1 > 0 || coef2 > 0) + { + const Integer tmp(coef1 * val); + num_tot1_ += tmp; + num_tot2_ += coef2 * val; + num_tot12_ += coef2 * tmp; + } + } + + void initialize() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + num_tot1_ = 0; + num_tot2_ = 0; + num_tot12_ = 0; + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef1(get_coef(reactants[0], *i)); + const Integer coef2(get_coef(reactants[1], *i)); + if (coef1 > 0 || coef2 > 0) + { + const Integer num(world().num_molecules_exact(*i)); + const Integer tmp(coef1 * num); + num_tot1_ += tmp; + num_tot2_ += coef2 * num; + num_tot12_ += coef2 * tmp; + } + } + } + + std::pair __draw() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + const Real rnd1(rng()->uniform(0.0, num_tot1_)); + + Integer num_tot(0), coef1(0); + std::vector::const_iterator itr1(species.begin()); + for (; itr1 != species.end(); ++itr1) + { + const Integer coef(get_coef(reactants[0], *itr1)); + if (coef > 0) + { + num_tot += coef * world().num_molecules_exact(*itr1); + if (num_tot >= rnd1) + { + coef1 = coef; + break; + } + } + } + + const Real rnd2( + rng()->uniform(0.0, num_tot2_ - get_coef(reactants[0], *itr1))); + + num_tot = 0; + for (std::vector::const_iterator i(species.begin()); + i != species.end(); ++i) + { + const Integer coef(get_coef(reactants[1], *i)); + if (coef > 0) + { + const Integer num(world().num_molecules_exact(*i)); + num_tot += coef * (i == itr1 ? num - 1 : num); + if (num_tot >= rnd2) + { + ReactionRule::reactant_container_type exact_reactants(2); + exact_reactants[0] = *itr1; + exact_reactants[1] = *i; + return std::make_pair(exact_reactants, coef1 * coef); + } + } + } + + return std::make_pair(ReactionRule::reactant_container_type(), 0); + } + + const Real propensity() const + { + const Integer num = num_tot1_ * num_tot2_ - num_tot12_; + return (num > 0 ? num * rr_.k() / world().volume() : 0.0); + } + + protected: + + Integer num_tot1_, num_tot2_, num_tot12_; + }; + + class DescriptorReactionRuleEvent + : public ReactionRuleEvent + { + public: + + typedef ReactionRuleEvent base_type; + typedef ReactionRuleDescriptor::state_container_type state_container_type; + + DescriptorReactionRuleEvent() + : base_type(), num_reactants_(), num_products_() + { + ; + } + + DescriptorReactionRuleEvent(GillespieSimulator* sim, const ReactionRule& rr) + : base_type(sim, rr), num_reactants_(), num_products_() + { + ; + } + + void inc(const Species& sp, const Integer val = +1) + { + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + for (std::size_t i = 0; i < reactants.size(); ++i) + { + const Integer coef(get_coef(reactants[i], sp)); + if (coef > 0) + { + num_reactants_[i] += coef * val; + } + } + + const ReactionRule::product_container_type& products(rr_.products()); + for (std::size_t i = 0; i < products.size(); ++i) + { + const Integer coef(get_coef(products[i], sp)); + if (coef > 0) + { + num_products_[i] += coef * val; + } + } + } + + void initialize() + { + const std::vector& species(world().list_species()); + + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + std::fill(num_reactants_.begin(), num_reactants_.end(), 0); + num_reactants_.resize(reactants.size(), 0); + const ReactionRule::product_container_type& products(rr_.products()); + std::fill(num_products_.begin(), num_products_.end(), 0); + num_products_.resize(products.size(), 0); + for (std::vector::const_iterator it(species.begin()); + it != species.end(); ++it) + { + const Species& sp(*it); + + for (std::size_t i = 0; i < reactants.size(); ++i) + { + const Integer coef(get_coef(reactants[i], sp)); + if (coef > 0) + { + num_reactants_[i] += coef * world().num_molecules_exact(sp); + } + } + + for (std::size_t i = 0; i < products.size(); ++i) + { + const Integer coef(get_coef(products[i], sp)); + if (coef > 0) + { + num_products_[i] += coef * world().num_molecules_exact(sp); + } + } + } + } + + std::pair __draw() + { + const std::vector& species(world().list_species()); + const ReactionRule::reactant_container_type& reactants(rr_.reactants()); + + std::pair ret; + ret.second = 1; + + for (std::size_t i = 0; i < reactants.size(); ++i) + { + assert(num_reactants_[i] > 0); + const Real rnd(rng()->uniform(0.0, num_reactants_[i])); + Integer num_tot(0); + for (std::vector::const_iterator it(species.begin()); + it != species.end(); ++it) + { + const Species& sp(*it); + const Integer coef(get_coef(reactants[i], sp)); + if (coef > 0) + { + num_tot += coef * world().num_molecules_exact(sp); + if (num_tot >= rnd) + { + ret.first.push_back(sp); + ret.second *= coef; + break; + } + } + } + } + + assert(ret.first.size() == reactants.size()); + return ret; + } + + const Real propensity() const + { + assert(rr_.has_descriptor()); + const std::shared_ptr& ratelaw = rr_.get_descriptor(); + assert(ratelaw->is_available()); + const Real ret = ratelaw->propensity(num_reactants_, num_products_, world().volume(), world().t()); + return ret; + } + + protected: + + state_container_type num_reactants_, num_products_; + }; + +public: + + GillespieSimulator( + std::shared_ptr world, + std::shared_ptr model) + : base_type(world, model) + { + initialize(); + } + + GillespieSimulator(std::shared_ptr world) + : base_type(world) + { + initialize(); + } + + // SimulatorTraits + Real dt(void) const; + + void step(void) ; + bool step(const Real & upto); + + // Optional members + + virtual bool check_reaction() const + { + return last_reactions_.size() > 0; + } + + std::vector > last_reactions() const + { + return last_reactions_; + } + + /** + * recalculate reaction propensities and draw the next time. + */ + void initialize(); + + inline std::shared_ptr rng() + { + return (*world_).rng(); + } + +protected: + + bool __draw_next_reaction(void); + void draw_next_reaction(void); + void increment_molecules(const Species& sp); + void decrement_molecules(const Species& sp); + void check_model(void); + +protected: + + Real dt_; + ReactionRule next_reaction_rule_, next_reaction_; + std::vector > last_reactions_; + + boost::ptr_vector events_; +}; + +} + +} // ecell4 + +#endif /* ECELL4_GILLESPIE_GILLESPIE_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/GillespieWorld.cpp",".cpp","3796","155","#include +#include +#include +#include + +#include +#include ""GillespieWorld.hpp"" + + +// using namespace std; + +namespace ecell4 +{ + +namespace gillespie +{ + +void GillespieWorld::set_t(const Real& t) +{ + this->cs_->set_t(t); +} + +const Real GillespieWorld::t() const +{ + return this->cs_->t(); +} + +std::vector GillespieWorld::list_species() const +{ + return this->cs_->list_species(); +} + +Integer GillespieWorld::num_molecules(const Species& sp) const +{ + return this->cs_->num_molecules(sp); +} + +Integer GillespieWorld::num_molecules_exact(const Species& sp) const +{ + return this->cs_->num_molecules_exact(sp); +} + +Real GillespieWorld::get_value(const Species& sp) const +{ + return this->cs_->get_value(sp); +} + +Real GillespieWorld::get_value_exact(const Species& sp) const +{ + return this->cs_->get_value_exact(sp); +} + +void GillespieWorld::set_value(const Species& sp, const Real value) +{ + this->cs_->set_value(sp, value); +} + +void GillespieWorld::add_molecules(const Species& sp, const Integer& num) +{ + this->cs_->add_molecules(sp, num); +} + +void GillespieWorld::remove_molecules(const Species& sp, const Integer& num) +{ + this->cs_->remove_molecules(sp, num); +} + +bool GillespieWorld::has_species(const Species& sp) const +{ + return this->cs_->has_species(sp); +} + +std::vector > + GillespieWorld::list_particles() const +{ + SerialIDGenerator pidgen; + const std::vector species_list(list_species()); + const Real3 lengths(edge_lengths()); + + std::vector > retval; + for (std::vector::const_iterator i(species_list.begin()); + i != species_list.end(); ++i) + { + const Integer num(num_molecules_exact(*i)); + + for (Integer k(0); k < num; ++k) + { + const Real3 pos( + rng_->uniform(0, lengths[0]), + rng_->uniform(0, lengths[1]), + rng_->uniform(0, lengths[2])); + retval.push_back( + std::make_pair(pidgen(), Particle(*i, pos, 0.0, 0.0))); + } + } + return retval; +} + +std::vector > + GillespieWorld::list_particles_exact(const Species& sp) const +{ + SerialIDGenerator pidgen; + const Real3 lengths(edge_lengths()); + + std::vector > retval; + const Integer num(num_molecules_exact(sp)); + + for (Integer k(0); k < num; ++k) + { + const Real3 pos( + rng_->uniform(0, lengths[0]), + rng_->uniform(0, lengths[1]), + rng_->uniform(0, lengths[2])); + retval.push_back( + std::make_pair(pidgen(), Particle(sp, pos, 0.0, 0.0))); + } + return retval; +} + +std::vector > + GillespieWorld::list_particles(const Species& sp) const +{ + SerialIDGenerator pidgen; + const std::vector species_list(list_species()); + const Real3 lengths(edge_lengths()); + + std::vector > retval; + for (std::vector::const_iterator i(species_list.begin()); + i != species_list.end(); ++i) + { + const Integer coef(count_species_matches(sp, *i)); + if (coef == 0) + { + continue; + } + + const Integer num(coef * num_molecules_exact(*i)); + + for (Integer k(0); k < num; ++k) + { + const Real3 pos( + rng_->uniform(0, lengths[0]), + rng_->uniform(0, lengths[1]), + rng_->uniform(0, lengths[2])); + retval.push_back( + std::make_pair(pidgen(), Particle(*i, pos, 0.0, 0.0))); + } + } + return retval; +} + +} // gillespie + +} // ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/GillespieWorld.hpp",".hpp","5539","198","#ifndef ECELL4_GILLESPIE_GILLESPIE_WORLD_HPP +#define ECELL4_GILLESPIE_GILLESPIE_WORLD_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#ifdef WITH_HDF5 +#include +#endif +#include +#include +#include +#include + + +namespace ecell4 +{ + +namespace gillespie +{ + +class GillespieWorld + : public WorldInterface +{ +public: + + GillespieWorld(const Real3& edge_lengths, + std::shared_ptr rng) + : cs_(new CompartmentSpaceVectorImpl(edge_lengths)), rng_(rng) + { + ; + } + + GillespieWorld(const Real3& edge_lengths = Real3(1, 1, 1)) + : cs_(new CompartmentSpaceVectorImpl(edge_lengths)) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); + } + + GillespieWorld(const std::string filename) + : cs_(new CompartmentSpaceVectorImpl(Real3(1, 1, 1))) + { + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + this->load(filename); + } + + const Real t() const; + void set_t(const Real& t); + + const Real3& edge_lengths() const + { + return cs_->edge_lengths(); + } + + void reset(const Real3& edge_lengths) + { + cs_->reset(edge_lengths); + } + + const Real volume() const + { + return cs_->volume(); + } + + Integer num_molecules(const Species& sp) const; + Integer num_molecules_exact(const Species& sp) const; + Real get_value(const Species& sp) const; + Real get_value_exact(const Species& sp) const; + void set_value(const Species& sp, const Real value); + std::vector list_species() const; + bool has_species(const Species& sp) const; + + void set_volume(const Real& volume) + { + (*cs_).set_volume(volume); + } + + void add_molecules(const Species& sp, const Integer& num); + void remove_molecules(const Species& sp, const Integer& num); + + inline const std::shared_ptr& rng() + { + return rng_; + } + + void save(const std::string& filename) const + { +#ifdef WITH_HDF5 + std::unique_ptr + fout(new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + rng_->save(fout.get()); + std::unique_ptr + group(new H5::Group(fout->createGroup(""CompartmentSpace""))); + cs_->save_hdf5(group.get()); + extras::save_version_information(fout.get(), std::string(""ecell4-gillespie-"") + std::string(VERSION_INFO)); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void load(const std::string& filename) + { +#ifdef WITH_HDF5 + std::unique_ptr + fin(new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-gillespie-0.0""; + try + { + const std::string version = extras::load_version_information(*fin); + if (!extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required << ""] or later is required.""; + throw NotSupported(ss.str()); + } + } + catch(H5::GroupIException not_found_error) + { + throw NotFound(""No version information was found.""); + } + + rng_->load(*fin); + const H5::Group group(fin->openGroup(""CompartmentSpace"")); + cs_->load_hdf5(group); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void bind_to(std::shared_ptr model) + { + if (std::shared_ptr bound_model = lock_model()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to GillespieWorld."" + << std::endl; + } + } + + this->model_ = model; + } + + std::shared_ptr lock_model() const + { + return model_.lock(); + } + + void add_molecules(const Species& sp, const Integer& num, const std::shared_ptr shape) + { + add_molecules(sp, num); + } + + std::pair, bool> new_particle(const Particle& p) + { + add_molecules(p.species(), 1); + return std::make_pair(std::make_pair(ParticleID(), p), true); + } + + std::pair, bool> new_particle( + const Species& sp, const Real3& pos) + { + add_molecules(sp, 1); + return std::make_pair( + std::make_pair(ParticleID(), Particle(sp, pos, 0.0, 0.0)), true); + } + + std::vector > list_particles() const; + std::vector > list_particles_exact(const Species& sp) const; + std::vector > list_particles(const Species& sp) const; + +private: + + std::unique_ptr cs_; + std::shared_ptr rng_; + + std::weak_ptr model_; +}; + +} // gillespie + +} // ecell4 + +#endif /* ECELL4_GILLESPIE_GILLESPIE_WORLD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/samples/simple.cpp",".cpp","1612","54","#include + +#include +#include +#include + +using namespace ecell4; +using namespace ecell4::gillespie; + + +int main(int argc, char **argv) +{ + Species sp1(""A""), sp2(""B""), sp3(""C""); + const Real kf(0.25), kr(1.0); + ReactionRule + rr1(create_binding_reaction_rule(sp1, sp2, sp3, kf)), + rr2(create_unbinding_reaction_rule(sp3, sp1, sp2, kr)); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + model->add_reaction_rule(rr1); + model->add_reaction_rule(rr2); + + std::shared_ptr + rng(new GSLRandomNumberGenerator()); + rng->seed(time(NULL)); + + const Real L(1.0); + const Real3 edge_lengths(L, L, L); + std::shared_ptr world(new GillespieWorld(edge_lengths, rng)); + world->add_molecules(sp3, 10); + world->save(""test_gillespie.h5""); + + GillespieSimulator sim(world, model); + + std::cout << ""t = "" << sim.t() + << "", A: "" << world->num_molecules(sp1) + << "", B: "" << world->num_molecules(sp2) + << "", C: "" << world->num_molecules(sp3) << std::endl; + for (int i = 0; i < 100; ++i) + { + sim.step(); + + std::cout << ""t = "" << sim.t() + << "", A: "" << world->num_molecules(sp1) + << "", B: "" << world->num_molecules(sp2) + << "", C: "" << world->num_molecules(sp3) << std::endl; + } + + return 0; +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/tests/GillespieSimulator_test.cpp",".cpp","1330","50","#define BOOST_TEST_MODULE ""GillespieSimulator_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include + +#include +#include + +using namespace ecell4; +using namespace ecell4::gillespie; + +BOOST_AUTO_TEST_CASE(GillespieSimulator_test_step) +{ + std::shared_ptr model(new NetworkModel()); + Species sp1(""A""); + Species sp2(""B""); + ReactionRule rr1; + rr1.set_k(5.0); + rr1.add_reactant(sp1); + rr1.add_product(sp2); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_reaction_rule(rr1); + + const Real L(1.0); + const Real3 edge_lengths(L, L, L); + std::shared_ptr rng(new GSLRandomNumberGenerator()); + std::shared_ptr world(new GillespieWorld(edge_lengths, rng)); + + world->add_molecules(sp1, 10); + world->add_molecules(sp2, 10); + + GillespieSimulator sim(world, model); + + sim.set_t(0.0); + sim.step(); + + BOOST_CHECK(0 < sim.t()); + BOOST_CHECK(world->num_molecules(sp1) == 9); + +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/gillespie/tests/GillespieWorld_test.cpp",".cpp","1075","40"," +#define BOOST_TEST_MODULE ""GillespieWorld_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include +#include +#include + +#include +#include + +using namespace ecell4; +using namespace ecell4::gillespie; + +BOOST_AUTO_TEST_CASE(GillespieWorld_test) +{ + std::shared_ptr rng(new GSLRandomNumberGenerator()); + rng->seed(time(NULL)); + Species sp1(""A""); + Species sp2(""B""); + + const Real L(1.0); + const Real3 edge_lengths(L, L, L); + std::shared_ptr world(new GillespieWorld(edge_lengths, rng)); + + world->add_molecules(sp1, 10); + world->add_molecules(sp2, 20); + world->set_t(0.5); + + BOOST_CHECK(world->t() == 0.5); + BOOST_CHECK(world->num_molecules(sp1) == 10); + BOOST_CHECK(world->num_molecules(sp2) == 20); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteReactions.cpp",".cpp","15181","457","#include ""SpatiocyteReactions.hpp"" +#include ""SpatiocyteWorld.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +// Utilities + +inline const std::string get_serial(std::shared_ptr world, + const Voxel &voxel) +{ + return voxel.get_voxel_pool()->species().serial(); +} + +inline const std::string get_location(std::shared_ptr world, + const Voxel &voxel) +{ + std::shared_ptr mtype(voxel.get_voxel_pool()); + if (mtype->is_vacant()) + return """"; + return mtype->location()->species().serial(); +} + +static inline void make_product(std::shared_ptr world, + ReactionInfo &rinfo, const Species &species, + const Voxel voxel) +{ + if (world->has_species(species) && + world->find_voxel_pool(species)->is_structure()) + { + if (boost::optional new_pid = + world->new_voxel_structure(species, voxel)) + { + rinfo.add_product(ReactionInfo::Item(*new_pid, species, voxel)); + } + } + else + { + if (boost::optional new_pid = + world->new_particle(species, voxel)) + { + rinfo.add_product(ReactionInfo::Item(*new_pid, species, voxel)); + } + } +} + +// Application of reactions + +ReactionInfo apply_a2b(std::shared_ptr world, + const ReactionInfo::Item &reactant_item, + const Species &product_species) +{ + const Voxel voxel(reactant_item.voxel); + const std::string bloc(world->get_molecule_info(product_species).loc); + const std::string aserial(get_serial(world, voxel)); + const std::string aloc(get_location(world, voxel)); + const std::string bserial(product_species.serial()); + + ReactionInfo rinfo(world->t()); + + if (aserial == bloc || aloc == bloc || aloc == bserial) + { + // A is the location of B (B can be placed on A), + // or A is on the location of B, + // or A is on B. + rinfo.add_reactant(reactant_item); + + if (aserial != bloc) + { + // Remove A once if A is not the location of B + voxel.clear(); + } + + if (aloc != bserial) + { + // Place a new B-molecule at the position of A + make_product(world, rinfo, product_species, voxel); + } + else + { + // When B is the location of A, it's enough to remove A + std::pair id_species_pair( + world->get_voxel_at(voxel)); + rinfo.add_product(ReactionInfo::Item( + id_species_pair.first, id_species_pair.second, voxel)); + } + } + else + { + // A is NOT on the location of B. + // B must be released into a neighbor, which is the location of B + if (boost::optional neighbor = + world->check_neighbor(voxel, bloc)) + { + // The neighbor is the location of B. + // Place B at the neighbor, and remove A. + rinfo.add_reactant(reactant_item); + + voxel.clear(); + + make_product(world, rinfo, product_species, *neighbor); + } + } + return rinfo; +} + +ReactionInfo apply_a2bc(std::shared_ptr world, + const ReactionInfo::Item &reactant_item, + const Species &product_species0, + const Species &product_species1) +{ + // A (pinfo) becomes B and C (product_species0 and product_species1) + // At least, one of A and B must be placed at the neighbor. + const Voxel voxel(reactant_item.voxel); + const std::string bserial(product_species0.serial()), + cserial(product_species1.serial()), + bloc(world->get_molecule_info(product_species0).loc), + cloc(world->get_molecule_info(product_species1).loc); + const std::string aserial(get_serial(world, voxel)); + const std::string aloc(get_location(world, voxel)); + + ReactionInfo rinfo(world->t()); + + if (aserial == bloc || aloc == bloc || aloc == bserial) + { + // A is the locaiton of B, + // or A is on the location of B, + // or B is the location of A + // C must be placed at the neighbor + + boost::optional neighbor(world->check_neighbor(voxel, cloc)); + + if (!neighbor) + { + // TODO: C cannot be on the neighbor. + return rinfo; + } + + const std::string nserial(get_serial(world, *neighbor)); + const std::string nloc(get_location(world, *neighbor)); + + rinfo.add_reactant(reactant_item); + + if (aserial != bloc) + { + // Remove A once if A is not the location of a new B-molecule + voxel.clear(); + } + + // No need to remove the neighbor because it's the location of C + // neighbor.first.clear(); + + if (aloc != bserial) + { + // Place a new B-molecule at the position of A + make_product(world, rinfo, product_species0, voxel); + } + else + { + // When B is the location of A, it's enough to remove A + std::pair id_species_pair( + world->get_voxel_at(voxel)); + rinfo.add_product(ReactionInfo::Item( + id_species_pair.first, id_species_pair.second, voxel)); + } + + // Place a new C-molecule at the neighbor + make_product(world, rinfo, product_species1, *neighbor); + + return rinfo; + } + else if (aserial == cloc || aloc == cloc || aloc == cserial) + { + // A is the locaiton of C, + // or A is on the location of C, + // or C is the location of A + // B must be placed at the neighbor + boost::optional neighbor(world->check_neighbor(voxel, bloc)); + + if (!neighbor) + { + // TODO: B cannot be on the neighbor. + return rinfo; + } + + const std::string nserial(get_serial(world, *neighbor)); + const std::string nloc(get_location(world, *neighbor)); + + rinfo.add_reactant(reactant_item); + + if (aserial != cloc) + { + // Remove A once if A is not the location of a new C-molecule + voxel.clear(); + } + + // No need to remove the neighbor because it's the location of B + // neighbor.first.clear(); + + // Place a new B-molecule at the neighbor + make_product(world, rinfo, product_species0, *neighbor); + + if (aloc != cserial) + { + // Place a new C-molecule at the position of A + make_product(world, rinfo, product_species1, voxel); + } + else + { + // When C is the location of A, it's enough to remove A + std::pair id_species_pair( + world->get_voxel_at(voxel)); + rinfo.add_product(ReactionInfo::Item( + id_species_pair.first, id_species_pair.second, voxel)); + } + return rinfo; + } + return rinfo; +} + +ReactionInfo apply_vanishment(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1) +{ + ReactionInfo rinfo(world->t()); + rinfo.add_reactant(reactant_item0); + rinfo.add_reactant(reactant_item1); + + reactant_item0.voxel.clear(); + reactant_item1.voxel.clear(); + + return rinfo; +} + +ReactionInfo apply_ab2c(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1, + const Species &product_species) +{ + const Voxel voxel0(reactant_item0.voxel); + const Voxel voxel1(reactant_item1.voxel); + + // A and B (from_info and to_info) become C (product_species) + const std::string location(world->get_molecule_info(product_species).loc); + const std::string fserial(get_serial(world, voxel0)); + const std::string floc(get_location(world, voxel0)); + const std::string tserial(get_serial(world, voxel1)); + const std::string tloc(get_location(world, voxel1)); + + ReactionInfo rinfo(world->t()); + + if (tserial == location || tloc == location) + { + // B is on the location of C, or the location itself. + // Place C at the coordinate of B, and remove A. + rinfo.add_reactant(reactant_item0); + rinfo.add_reactant(reactant_item1); + + if (tserial != location) + { + voxel1.clear(); + } + + voxel0.clear(); + + make_product(world, rinfo, product_species, voxel1); + } + else if (fserial == location || floc == location) + { + // A is on the location of C, or the location itself. + // Place C at the coordinate of A, and remove B. + rinfo.add_reactant(reactant_item0); + rinfo.add_reactant(reactant_item1); + + if (fserial != location) + { + voxel0.clear(); + } + + voxel1.clear(); + + make_product(world, rinfo, product_species, voxel0); + } + return rinfo; +} + +// For apply_ab2cd +ReactionInfo apply_ab2cd_in_order(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1, + const Species &product_species0, + const Species &product_species1, + const Voxel &voxel0, const Voxel &voxel1) +{ + ReactionInfo rinfo(world->t()); + rinfo.add_reactant(reactant_item0); + rinfo.add_reactant(reactant_item1); + + make_product(world, rinfo, product_species0, voxel0); + make_product(world, rinfo, product_species1, voxel1); + + return rinfo; +} + +ReactionInfo apply_ab2cd(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1, + const Species &product_species0, + const Species &product_species1) +{ + const Voxel &src(reactant_item0.voxel); + const Voxel &dst(reactant_item1.voxel); + + const std::string aserial(get_serial(world, src)); + const std::string aloc(get_location(world, src)); + const std::string bserial(get_serial(world, dst)); + const std::string bloc(get_location(world, dst)); + const std::string cloc(world->get_molecule_info(product_species0).loc); + const std::string dloc(world->get_molecule_info(product_species1).loc); + + if (aserial == cloc || aloc == cloc) + { + if (bserial == dloc || bloc == dloc) + { + if (aserial != cloc) + { + // Remove A once if A is not the location of C + src.clear(); + } + if (bserial != dloc) + { + // Remove B once if B is not the location of D + dst.clear(); + } + return apply_ab2cd_in_order(world, reactant_item0, reactant_item1, + product_species0, product_species1, src, + dst); + } + else + { + boost::optional neighbor(world->check_neighbor(dst, dloc)); + + if (neighbor) + { + dst.clear(); + if (aserial != cloc) + { + // Remove A once if A is not the location of C + src.clear(); + } + return apply_ab2cd_in_order(world, reactant_item0, + reactant_item1, product_species0, + product_species1, src, *neighbor); + } + } + } + else if (aserial == dloc || aloc == dloc) + { + if (bserial == cloc || bloc == dloc) + { + if (aserial != dloc) + { + // Remove A once if A is not the location of D + src.clear(); + } + if (bserial != cloc) + { + // Remove B once if B is not the location of C + dst.clear(); + } + return apply_ab2cd_in_order(world, reactant_item0, reactant_item1, + product_species0, product_species1, dst, + src); + } + else + { + boost::optional neighbor(world->check_neighbor(dst, cloc)); + + if (neighbor) + { + dst.clear(); + if (aserial != dloc) + { + // Remove A once if A is not the location of D + src.clear(); + } + return apply_ab2cd_in_order(world, reactant_item0, + reactant_item1, product_species0, + product_species1, *neighbor, src); + } + } + } + else if (bserial == cloc || bloc == cloc) + { + if (boost::optional neighbor = + (world->check_neighbor(dst, dloc))) + { + src.clear(); + if (bserial != cloc) + { + // Remove B once if B is not the location of C + dst.clear(); + } + return apply_ab2cd_in_order(world, reactant_item0, reactant_item1, + product_species0, product_species1, dst, + *neighbor); + } + } + else if (bserial == dloc || bloc == dloc) + { + if (boost::optional neighbor = world->check_neighbor(dst, dloc)) + { + src.clear(); + if (bserial != dloc) + { + // remove b once if b is not the location of d + dst.clear(); + } + return apply_ab2cd_in_order(world, reactant_item0, reactant_item1, + product_species0, product_species1, + *neighbor, dst); + } + } + return ReactionInfo(world->t()); +} + +ReactionInfo +apply_second_order_reaction(std::shared_ptr world, + const ReactionRule &reaction_rule, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1) +{ + const ReactionRule::product_container_type &products( + reaction_rule.products()); + + switch (products.size()) + { + case 0: + return apply_vanishment(world, reactant_item0, reactant_item1); + case 1: + return apply_ab2c(world, reactant_item0, reactant_item1, + products.at(0)); + case 2: + return apply_ab2cd(world, reactant_item0, reactant_item1, + products.at(0), products.at(1)); + default: + return ReactionInfo(world->t()); + } +} + +} // namespace spatiocyte + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteEvent.hpp",".hpp","7179","248","#ifndef ECELL4_SPATIOCYTE_EVENT_HPP +#define ECELL4_SPATIOCYTE_EVENT_HPP + +#include ""SpatiocyteReactions.hpp"" +#include ""SpatiocyteWorld.hpp"" +#include ""utils.hpp"" +#include +#include +#include + +namespace ecell4 +{ + +namespace spatiocyte +{ + +struct SpatiocyteEvent : public Event +{ +public: + typedef std::pair reaction_type; + + SpatiocyteEvent(Real const &time) : Event(time) {} + virtual ~SpatiocyteEvent() {} + + const std::vector &reactions() const { return reactions_; } + + virtual void fire() + { + reactions_.clear(); + fire_(); + } + +protected: + virtual void fire_() = 0; + + void push_reaction(const reaction_type &reaction) + { + reactions_.push_back(reaction); + } + + std::vector reactions_; +}; + +template +const Real calc_dt(const Real R, const Real D); + +template +struct StepEvent : SpatiocyteEvent +{ + StepEvent(std::shared_ptr model, + std::shared_ptr world, const Species &species, + const Real &t, const Real alpha = 1.0) + : SpatiocyteEvent(t), model_(model), world_(world), alpha_(alpha) + { + if (const auto space_and_molecule_pool = + world_->find_space_and_molecule_pool(species)) + { + space_ = space_and_molecule_pool->first; + mpool_ = space_and_molecule_pool->second; + } + else + { + throw ""MoleculePool is not found""; + } + + const MoleculeInfo minfo(world_->get_molecule_info(species)); + const Real D(minfo.D); + const Real R(world_->voxel_radius()); + + if (D <= 0) + dt_ = std::numeric_limits::infinity(); + else + dt_ = calc_dt(R, D) * alpha_; + + time_ = t + dt_; + } + + Species const &species() const { return mpool_->species(); } + + Real const &alpha() const { return alpha_; } + + void fire_() + { + walk(alpha_); + time_ += dt_; + } + + void walk(const Real &alpha) + { + if (alpha < 0 || alpha > 1) + { + return; // INVALID ALPHA VALUE + } + + MoleculePool::container_type voxels; + copy(mpool_->begin(), mpool_->end(), back_inserter(voxels)); + + std::size_t idx(0); + for (const auto &info : voxels) + { + const Voxel voxel(space_, info.coordinate); + + if (voxel.get_voxel_pool() != mpool_) + { + // should skip if a voxel is not the target species. + // when reaction has occured before, a voxel can be changed. + continue; + } + + const Voxel neighbor = + world_->get_neighbor_randomly(voxel); + + if (world_->can_move(voxel, neighbor)) + { + if (world_->rng()->uniform(0, 1) <= alpha) + world_->move(voxel, neighbor, /*candidate=*/idx); + } + else + { + attempt_reaction_(info, neighbor, alpha); + } + + ++idx; + } + } + +protected: + void attempt_reaction_(const SpatiocyteWorld::coordinate_id_pair_type &info, + const Voxel &dst, const Real &alpha) + { + const Voxel voxel(space_, info.coordinate); + std::shared_ptr from_mt(voxel.get_voxel_pool()); + std::shared_ptr to_mt(dst.get_voxel_pool()); + + const Species &speciesA(from_mt->species()); + const Species &speciesB(to_mt->species()); + + const std::vector rules( + model_->query_reaction_rules(speciesA, speciesB)); + + if (rules.empty()) + { + return; + } + + const Real from_D(world_->get_molecule_info(speciesA).D); + const Real to_D(world_->get_molecule_info(speciesB).D); + const Real factor( + calculate_dimensional_factor(from_mt, from_D, to_mt, to_D, world_)); + const Real rnd(world_->rng()->uniform(0, 1)); + Real accp(0.0); + + for (const auto &rule : rules) + { + const Real k(rule.k()); + const Real P(k * factor * alpha); + accp += P; + if (accp > 1 && k != std::numeric_limits::infinity()) + { + std::cerr << ""The total acceptance probability ["" << accp + << ""] exceeds 1 for '"" << speciesA.serial() + << ""' and '"" << speciesB.serial() << ""'."" + << std::endl; + } + if (accp >= rnd) + { + ReactionInfo rinfo(apply_second_order_reaction( + world_, rule, + ReactionInfo::Item(info.pid, from_mt->species(), voxel), + ReactionInfo::Item(to_mt->get_particle_id(dst.coordinate), + to_mt->species(), dst))); + if (rinfo.has_occurred()) + { + reaction_type reaction(std::make_pair(rule, rinfo)); + push_reaction(reaction); + } + return; + } + } + } + +protected: + std::shared_ptr model_; + std::shared_ptr world_; + std::weak_ptr space_; + std::shared_ptr mpool_; + + const Real alpha_; +}; + +struct ZerothOrderReactionEvent : SpatiocyteEvent +{ + ZerothOrderReactionEvent(std::shared_ptr world, + const ReactionRule &rule, const Real &t); + + virtual ~ZerothOrderReactionEvent() {} + virtual void fire_(); + + Real draw_dt(); + virtual void interrupt(Real const &t) { time_ = t + draw_dt(); } + +protected: + std::shared_ptr world_; + ReactionRule rule_; +}; + +struct FirstOrderReactionEvent : SpatiocyteEvent +{ + FirstOrderReactionEvent(std::shared_ptr world, + const ReactionRule &rule, const Real &t); + + virtual ~FirstOrderReactionEvent() {} + virtual void fire_(); + + Real draw_dt(); + virtual void interrupt(Real const &t) { time_ = t + draw_dt(); } + +protected: + ReactionInfo::Item choice() + { + const Species &species(rule_.reactants().at(0)); + if (const auto space_and_molecule_pool = + world_->find_space_and_molecule_pool(species)) + { + const auto space = space_and_molecule_pool->first; + const auto molecule_pool = space_and_molecule_pool->second; + + const auto i = + rng_.lock()->uniform_int(0, molecule_pool->size() - 1); + const auto &info = molecule_pool->at(i); + + return ReactionInfo::Item(info.pid, species, + Voxel(space, info.coordinate)); + } + throw ""MoleculePool is not found""; + } + + std::shared_ptr world_; + std::weak_ptr rng_; + ReactionRule rule_; +}; + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_SPATIOCYTE_EVENT_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteFactory.hpp",".hpp","1829","78","#ifndef ECELL4_LATTICE_LATTICE_FACTORY_HPP +#define ECELL4_LATTICE_LATTICE_FACTORY_HPP + +#include +#include + +#include ""SpatiocyteSimulator.hpp"" +#include ""SpatiocyteWorld.hpp"" +#include + +namespace ecell4 +{ + +namespace spatiocyte +{ + +class SpatiocyteFactory + : public SimulatorFactory { +public: + typedef SimulatorFactory base_type; + typedef base_type::world_type world_type; + typedef base_type::simulator_type simulator_type; + typedef SpatiocyteFactory this_type; + +public: + SpatiocyteFactory(const Real voxel_radius = default_voxel_radius()) + : base_type(), rng_(), voxel_radius_(voxel_radius) + { + ; // do nothing + } + + virtual ~SpatiocyteFactory() + { + ; // do nothing + } + + static inline const Real default_voxel_radius() { return 0.0; } + + this_type &rng(const std::shared_ptr &rng) + { + rng_ = rng; + return (*this); + } + + inline this_type * + rng_ptr(const std::shared_ptr &rng) + { + return &(this->rng(rng)); // XXX: == this + } + +protected: + virtual world_type *create_world(const Real3 &edge_lengths) const + { + if (rng_) + { + return new world_type(edge_lengths, voxel_radius_, rng_); + } + else if (voxel_radius_ > 0) + { + return new world_type(edge_lengths, voxel_radius_); + } + else + { + return new world_type(edge_lengths); + } + } + +protected: + std::shared_ptr rng_; + Real voxel_radius_; +}; + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_LATTICE_LATTICE_FACTORY_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteWorld.cpp",".cpp","11744","427","#include +#include + +#include ""SpatiocyteWorld.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +void SpatiocyteWorld::add_space(std::unique_ptr uniq_space) +{ + std::shared_ptr space(uniq_space.release()); + + for (auto i(0); i < space->size(); ++i) + { + const Voxel voxel(space, i); + const auto position(voxel.position()); + const Voxel nearest(get_root(), + get_root()->position2coordinate(position)); + + for (Integer j(0); j < num_neighbors(nearest); ++j) + { + const auto neighbor(get_neighbor(nearest, j)); + if (length(neighbor.position() - position) < voxel_radius() * 2) + { + interfaces_.add(neighbor, voxel); + } + } + } + + for (const auto &interface : interfaces_) + { + const Voxel voxel(interface.first); + + std::vector neighbors; + for (auto i(0); i < num_neighbors(voxel); ++i) + { + const auto neighbor(get_neighbor(voxel, i)); + + if (!interfaces_.find(neighbor)) + { + neighbors.push_back(neighbor); + } + } + + for (const auto &adjoining : interface.second) + { + neighbors_.extend(adjoining, neighbors); + } + } + + size_ += space->size(); + spaces_.push_back(space); +} + +void SpatiocyteWorld::set_value(const Species &sp, const Real value) +{ + const Integer num1 = static_cast(value); + const Integer num2 = num_molecules_exact(sp); + if (num1 > num2) + { + add_molecules(sp, num1 - num2); + } + else if (num1 < num2) + { + remove_molecules(sp, num2 - num1); + } +} + +std::vector> +SpatiocyteWorld::list_structure_particles() const +{ + const std::vector structure_species(list_structure_species()); + + typedef std::vector>> tmp_type; + tmp_type tmp_vector(structure_species.size()); + Integer num_elements(0); + + for (const auto &species : structure_species) + { + std::vector> tmp( + list_particles(species)); + tmp_vector.push_back(tmp); + num_elements += tmp.size(); + } + + std::vector> retval; + retval.reserve(num_elements); + for (const auto &tmp : tmp_vector) + { + retval.insert(retval.end(), tmp.begin(), tmp.end()); + } + + return retval; +} + +std::vector> +SpatiocyteWorld::list_non_structure_particles() const +{ + const std::vector non_structure_species( + list_non_structure_species()); + + typedef std::vector>> tmp_type; + tmp_type tmp_vector(non_structure_species.size()); + Integer num_elements(0); + + for (const auto &species : non_structure_species) + { + std::vector> tmp( + list_particles(species)); + tmp_vector.push_back(tmp); + num_elements += tmp.size(); + } + + std::vector> retval; + retval.reserve(num_elements); + for (const auto &tmp : tmp_vector) + { + retval.insert(retval.end(), tmp.begin(), tmp.end()); + } + + return retval; +} + +std::vector SpatiocyteWorld::list_non_structure_species() const +{ + std::vector retval; + for (const auto &species : list_species()) + { + if (!find_voxel_pool(species)->is_structure()) + retval.push_back(species); + } + return retval; +} + +std::vector SpatiocyteWorld::list_structure_species() const +{ + std::vector retval; + for (const auto &species : list_species()) + { + if (find_voxel_pool(species)->is_structure()) + retval.push_back(species); + } + return retval; +} + +bool SpatiocyteWorld::add_molecules(const Species &sp, const Integer &num) +{ + if (num < 0) + { + throw std::invalid_argument( + ""The number of molecules must be positive.""); + } + + const MoleculeInfo info(get_molecule_info(sp)); + + if (const auto space_and_location = + find_space_and_voxel_pool(Species(info.loc))) + { + const auto space = space_and_location->first; + const auto location = space_and_location->second; + + if (location->size() < num) + return false; + + auto count(0); + while (count < num) + { + const Voxel voxel(space, rng()->uniform_int(0, space->size() - 1)); + + if (voxel.get_voxel_pool() != location) + continue; + + if (new_particle(sp, voxel)) + ++count; + } + return true; + } + return false; +} + +bool SpatiocyteWorld::add_molecules(const Species &sp, const Integer &num, + const std::shared_ptr shape) +{ + if (num < 0) + { + throw std::invalid_argument( + ""The number of molecules must be positive.""); + } + + const MoleculeInfo info(get_molecule_info(sp)); + + Integer count(0); + while (count < num) + { + const Real3 pos(shape->draw_position(rng_)); + const Voxel voxel(get_voxel_nearby(pos)); + + if (voxel.get_voxel_pool()->species().serial() != info.loc) + { + continue; + } + else if (new_particle(sp, voxel)) + { + ++count; + } + } + return true; +} + +Integer +SpatiocyteWorld::add_structure(const Species &sp, + const std::shared_ptr shape) +{ + const MoleculeInfo info(get_molecule_info(sp)); + get_root()->make_structure_type(sp, info.loc); + + if (shape->dimension() != info.dimension) + { + throw IllegalArgument(""The dimension mismatch occurred between a given "" + ""species and shape""); + } + + switch (shape->dimension()) + { + case Shape::THREE: + return add_structure3(sp, info.loc, shape); + case Shape::TWO: + return add_structure2(sp, info.loc, shape); + case Shape::ONE: + case Shape::UNDEF: + break; + } + + throw NotSupported(""The dimension of a shape must be two or three.""); +} + +Integer +SpatiocyteWorld::add_structure3(const Species &sp, const std::string &location, + const std::shared_ptr shape) +{ + Integer count(0); + for (const auto &space : spaces_) + { + for (auto coord(0); coord < space->size(); ++coord) + { + const Voxel voxel(space, coord); + // should check if coord doesn't point at the boundary. + if (!space->is_inside(coord) || + shape->is_inside(voxel.position()) > 0) + continue; + + if (voxel.get_voxel_pool()->species().serial() != location) + { + throw NotSupported( + ""Mismatch in the location. Failed to place '"" + + sp.serial() + ""' to '"" + + voxel.get_voxel_pool()->species().serial() + ""'. "" + ""'"" + + location + ""' is expected.""); + continue; + } + + if (new_voxel_structure(sp, voxel)) + ++count; + } + } + return count; +} + +Integer +SpatiocyteWorld::add_structure2(const Species &sp, const std::string &location, + const std::shared_ptr shape) +{ + Integer count(0); + for (const auto &space : spaces_) + { + for (auto coord(0); coord < space->size(); ++coord) + { + const Voxel voxel(space, coord); + // should check if coord doesn't point at the boundary. + if (!space->is_inside(coord) || !is_surface_voxel(voxel, shape)) + continue; + if (voxel.get_voxel_pool()->species().serial() != location) + { + throw NotSupported( + ""Mismatch in the location. Failed to place '"" + + sp.serial() + ""' to '"" + + voxel.get_voxel_pool()->species().serial() + ""'. "" + ""'"" + + location + ""' is expected.""); + continue; + } + + if (new_voxel_structure(sp, voxel)) + ++count; + } + } + return count; +} + +bool SpatiocyteWorld::is_surface_voxel( + const Voxel &voxel, const std::shared_ptr shape) const +{ + const Real L(shape->is_inside(voxel.position())); + if (L > 0 || L < -2 * voxel_radius()) + return false; + + for (Integer i(0); i < num_neighbors(voxel); ++i) + if (shape->is_inside(get_neighbor(voxel, i).position()) > 0) + return true; + + return false; +} + +void SpatiocyteWorld::remove_molecules(const Species &sp, const Integer &num) +{ + if (num < 0) + { + throw std::invalid_argument( + ""The number of molecules must be positive.""); + } + + if (const auto space_and_molecule_pool = find_space_and_molecule_pool(sp)) + { + const auto space = space_and_molecule_pool->first; + const auto molecule_pool = space_and_molecule_pool->second; + + if (molecule_pool->size() < num) + throw std::invalid_argument( + ""The number of molecules cannot be negative.""); + + auto count(0); + while (count < num) + { + const auto idx(rng_->uniform_int(0, molecule_pool->size() - 1)); + const Voxel voxel(space, molecule_pool->at(idx).coordinate); + if (voxel.clear()) + { + ++count; + } + } + } +} + +boost::optional SpatiocyteWorld::check_neighbor(const Voxel &voxel, + const std::string &loc) +{ + const std::size_t num(num_neighbors(voxel)); + + std::vector tmp; + tmp.reserve(num); + + for (unsigned int rnd(0); rnd < num; ++rnd) + { + const Voxel neighbor(get_neighbor(voxel, rnd)); + std::shared_ptr mt(neighbor.get_voxel_pool()); + if (mt->species().serial() == loc) + { + tmp.push_back(neighbor); + } + } + + if (const auto neighbors = neighbors_.find(voxel)) + { + for (const auto &neighbor : *neighbors) + { + if (neighbor.get_voxel_pool()->species().serial() == loc) + { + tmp.push_back(neighbor); + } + } + } + + if (tmp.size() == 0) + { + return boost::none; + } + + return tmp[rng()->uniform_int(0, tmp.size() - 1)]; +} + +template <> +const Voxel SpatiocyteWorld::get_neighbor_randomly<3>(const Voxel &voxel) +{ + const auto idx(rng()->uniform_int(0, num_neighbors(voxel) - 1)); + const auto neighbor = get_neighbor(voxel, idx); + + if (const auto neighbors = interfaces_.find(neighbor)) + { + const auto idx(rng()->uniform_int(0, neighbors->size() - 1)); + return neighbors->at(idx); + } + + return neighbor; +} + +template <> +const Voxel SpatiocyteWorld::get_neighbor_randomly<2>(const Voxel &voxel) +{ + std::vector neighbors; + for (Integer idx = 0; idx < num_neighbors(voxel); ++idx) + { + const Voxel neighbor = get_neighbor(voxel, idx); + if (get_dimension(neighbor.get_voxel_pool()->species()) > Shape::TWO) + { + continue; + } + neighbors.push_back(neighbor); + } + + const Integer idx(rng()->uniform_int(0, neighbors.size() - 1)); + const auto neighbor = neighbors.at(idx); + + if (const auto neighbors = interfaces_.find(neighbor)) + { + const auto idx(rng()->uniform_int(0, neighbors->size() - 1)); + return neighbors->at(idx); + } + + return neighbor; +} + +} // namespace spatiocyte + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/Voxel.hpp",".hpp","1376","65","#ifndef ECELL4_SPATIOCYTE_VOXEL_HPP +#define ECELL4_SPATIOCYTE_VOXEL_HPP + +#include +#include +#include +#include + +namespace ecell4 +{ + +namespace spatiocyte +{ + +class SpatiocyteWorld; + +struct Voxel +{ + typedef VoxelSpaceBase::coordinate_type coordinate_type; + + Voxel(std::weak_ptr space, coordinate_type coordinate) + : space(space), coordinate(coordinate) + { + } + + std::weak_ptr space; + coordinate_type coordinate; + +public: + const Real3 position() const + { + return space.lock()->coordinate2position(coordinate); + } + + bool clear() const { return space.lock()->remove_voxel(coordinate); } + + std::shared_ptr get_voxel_pool() const + { + return space.lock()->get_voxel_pool_at(coordinate); + } + + bool operator==(const Voxel &rhs) const noexcept + { + return space.lock() == rhs.space.lock() && coordinate == rhs.coordinate; + } +}; + +} // namespace spatiocyte + +} // namespace ecell4 + +namespace std { +template <> +struct hash +{ + std::size_t operator()(const ecell4::spatiocyte::Voxel &val) const + { + auto ptr = val.space.lock().get(); + return hash()(ptr) ^ + static_cast(val.coordinate); + } +}; +} // std +#endif +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteSimulator.hpp",".hpp","2546","96","#ifndef ECELL4_LATTICE_LATTICE_SIMULATOR_HPP +#define ECELL4_LATTICE_LATTICE_SIMULATOR_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include ""SpatiocyteEvent.hpp"" +#include ""SpatiocyteWorld.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +class SpatiocyteSimulator : public SimulatorBase { +public: + typedef SimulatorBase base_type; + typedef SpatiocyteEvent::reaction_type reaction_type; + typedef EventSchedulerBase scheduler_type; + typedef std::unordered_map alpha_map_type; + +public: + SpatiocyteSimulator(std::shared_ptr world, + std::shared_ptr model) + : base_type(world, model) + { + initialize(); + } + + SpatiocyteSimulator(std::shared_ptr world) + : base_type(world) + { + initialize(); + } + + virtual Real dt() const { return dt_; } + + void initialize(); + void finalize(); + void step(); + bool step(const Real &upto); + + virtual bool check_reaction() const { return last_reactions().size() > 0; } + + const std::vector &last_reactions() const + { + // return last_event_->reactions(); + return last_reactions_; + } + +protected: + std::shared_ptr + create_step_event(const Species &species, const Real &t, const Real &alpha); + std::shared_ptr + create_zeroth_order_reaction_event(const ReactionRule &reaction_rule, + const Real &t); + std::shared_ptr + create_first_order_reaction_event(const ReactionRule &reaction_rule, + const Real &t); + + void step_(); + void register_events(const Species &species); + void update_alpha_map(); + + void set_last_event_(std::shared_ptr event) + { + last_event_ = event; + } + +protected: + scheduler_type scheduler_; + std::shared_ptr last_event_; + alpha_map_type alpha_map_; + + std::vector last_reactions_; + + std::vector species_list_; + + Real dt_; +}; + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_LATTICE_LATTICE_SIMULATOR_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/OffLattice.hpp",".hpp","1881","68","#ifndef ECELL4_SPATIOCYTE_OFFLATTICE_HPP +#define ECELL4_SPATIOCYTE_OFFLATTICE_HPP + +#include +#include + +namespace ecell4 +{ + +namespace spatiocyte { + +class OffLattice { +public: + using positions_type = OffLatticeSpace::position_container; + using adjoining_pairs_type = OffLatticeSpace::coordinate_pair_list_type; + + OffLattice(const Real voxel_radius, const positions_type positions, const adjoining_pairs_type adjoining_pairs) + : voxel_radius_(voxel_radius), positions_(positions), adjoining_pairs_(adjoining_pairs) {} + + OffLattice(const Real voxel_radius, const positions_type positions) + : voxel_radius_(voxel_radius), positions_(positions) + { + constexpr Real epsilon = std::numeric_limits::epsilon(); + + adjoining_pairs_.clear(); + const std::size_t size = positions_.size(); + for (std::size_t i(0); i < size; ++i) + for (std::size_t j(i+1); j < size; ++j) + if (length(positions_[j] - positions_[i]) <= voxel_radius_ + epsilon) + { + adjoining_pairs_.push_back(std::make_pair(i, j)); + } + } + + inline const Real& voxel_radius() const + { + return voxel_radius_; + } + + inline const positions_type& positions() const + { + return positions_; + } + + inline const adjoining_pairs_type& adjoining_pairs() const + { + return adjoining_pairs_; + } + + std::unique_ptr generate_space(const Species& species) const + { + return std::unique_ptr( + new OffLatticeSpace(voxel_radius_, species, positions_, adjoining_pairs_)); + } + +protected: + + Real voxel_radius_; + positions_type positions_; + adjoining_pairs_type adjoining_pairs_; +}; + +} // spatiocyte + +} // ecell4 + +#endif /* ECELL4_SPATIOCYTE_OFFLATTICE_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/StepEvent.cpp",".cpp","311","24","#include ""SpatiocyteEvent.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +template <> +const Real calc_dt<3>(const Real R, const Real D) +{ + return 2 * R * R / 3 / D; +} + +template <> +const Real calc_dt<2>(const Real R, const Real D) +{ + return R * R / D; +} + +} // namespace spatiocyte + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/utils.cpp",".cpp","3456","109","#include ""utils.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +const Real calculate_dimensional_factor( + std::shared_ptr mt0, const Real D_A, + std::shared_ptr mt1, const Real D_B, + std::shared_ptr world) +{ + const Real voxel_radius(world->voxel_radius()); + const Real unit_area(world->unit_area()); + + const Species speciesA(mt0->species()), speciesB(mt1->species()); + const Shape::dimension_kind dimensionA(world->get_dimension(speciesA)), + dimensionB(world->get_dimension(speciesB)); + const Real Dtot(D_A + D_B); + const Real gamma( + pow(2 * sqrt(2.0) + 4 * sqrt(3.0) + 3 * sqrt(6.0) + sqrt(22.0), 2) / + (72 * (6 * sqrt(2.0) + 4 * sqrt(3.0) + 3 * sqrt(6.0)))); + Real factor(0); + if (dimensionA == Shape::THREE && dimensionB == Shape::THREE) + { + // if (speciesA != speciesB) + // factor = 1. / (6 * sqrt(2.0) * Dtot * voxel_radius); + // else + // factor = 1. / (6 * sqrt(2.0) * D_A * voxel_radius); + factor = 1. / (6 * sqrt(2.0) * Dtot * voxel_radius); + } + else if (dimensionA == Shape::TWO && dimensionB == Shape::TWO) + { + // if (speciesA != speciesB) + // factor = gamma / Dtot; + // else + // factor = gamma / D_A; + factor = gamma / Dtot; + } + else if (dimensionA == Shape::THREE && dimensionB == Shape::TWO) + { + factor = sqrt(2.0) / (3 * D_A * voxel_radius); + if (mt1->is_structure()) // B is Surface + { + factor *= unit_area; + } + } + else if (dimensionA == Shape::TWO && dimensionB == Shape::THREE) + { + factor = sqrt(2.0) / (3 * D_B * voxel_radius); + if (mt0->is_structure()) // A is Surface + { + factor *= unit_area; + } + } + else + throw NotSupported( + ""The dimension of a structure must be two or three.""); + return factor; +} + +const Real calculate_alpha(const ReactionRule &rr, + const std::shared_ptr &world) +{ + const ReactionRule::reactant_container_type &reactants(rr.reactants()); + if (reactants.size() != 2) + return 1.0; + else if (rr.k() == std::numeric_limits::infinity()) + return 1.0; + + const Species species[2] = {reactants.at(0), reactants.at(1)}; + const MoleculeInfo info[2] = {world->get_molecule_info(species[0]), + world->get_molecule_info(species[1])}; + std::shared_ptr mt[2]; + for (int i(0); i < 2; ++i) + { + try + { + mt[i] = world->find_voxel_pool(species[i]); + } + catch (NotFound e) + { + std::weak_ptr location(world->vacant()); + if (info[i].loc != """") + { + try + { + location = world->find_voxel_pool(Species(info[i].loc)); + } + catch (NotFound e) + { + ; + } + } + mt[i] = std::shared_ptr( + new MoleculePool(species[i], location)); + } + } + const Real factor(calculate_dimensional_factor(mt[0], info[0].D, mt[1], + info[1].D, world)); + const Real alpha(1.0 / (factor * rr.k())); + return alpha < 1.0 ? alpha : 1.0; +} + +} // namespace spatiocyte + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/utils.hpp",".hpp","570","25","#ifndef ECELL4_SPATIOCYTE_UTILS_HPP +#define ECELL4_SPATIOCYTE_UTILS_HPP + +#include ""SpatiocyteWorld.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +const Real calculate_dimensional_factor( + std::shared_ptr mt0, const Real D_A, + std::shared_ptr mt1, const Real D_B, + std::shared_ptr world); + +const Real calculate_alpha(const ReactionRule &rr, + const std::shared_ptr &world); + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_SPATIOCYTE_UTILS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/OneToManyMap.hpp",".hpp","1595","69","#ifndef ECELL4_SPATIOCYTE_INTERFACE_CONTAINER +#define ECELL4_SPATIOCYTE_INTERFACE_CONTAINER + +#include +#include +#include + +namespace ecell4 +{ + +namespace spatiocyte +{ + +template class OneToManyMap { + +protected: + typedef std::unordered_map> container_type; + + typedef typename container_type::iterator iterator; + +public: + typedef typename container_type::const_iterator const_iterator; + + OneToManyMap() {} + + void add(T key, T value) + { + iterator itr(container_.find(key)); + + if (itr != container_.end()) + (*itr).second.push_back(value); + else + container_.insert(std::make_pair(key, std::vector(1, value))); + } + + void extend(T key, std::vector values) + { + iterator itr(container_.find(key)); + + if (itr != container_.end()) + std::copy(values.begin(), values.end(), + back_inserter((*itr).second)); + else + container_.insert(std::make_pair(key, values)); + } + + boost::optional &> find(const T &key) const + { + const_iterator itr(container_.find(key)); + + if (itr != container_.end()) + return (*itr).second; + return boost::none; + } + + const_iterator begin() const { return container_.begin(); } + const_iterator end() const { return container_.end(); } + +protected: + container_type container_; + +}; // class OneToManyMap + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_SPATIOCYTE_INTERFACE_CONTAINER */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteReactions.hpp",".hpp","3186","107","#ifndef ECELL4_SPATIOCYTE_REACTIONS_HPP +#define ECELL4_SPATIOCYTE_REACTIONS_HPP + +#include +#include ""Voxel.hpp"" +#include +#include + +namespace ecell4 +{ + +namespace spatiocyte +{ + +class ReactionInfo { +public: + struct Item + { + Item(ParticleID pid, const Species &species, const Voxel &voxel) + : pid(pid), species(species), voxel(voxel) + { + } + + ParticleID pid; + Species species; + Voxel voxel; + }; + + typedef std::vector container_type; + +public: + ReactionInfo() : t_(0), reactants_(), products_() {} + + ReactionInfo(const Real t) : t_(t), reactants_(), products_() {} + + ReactionInfo(const Real t, const container_type &reactants, + const container_type &products) + : t_(t), reactants_(reactants), products_(products) + { + } + + ReactionInfo(const ReactionInfo &another) + : t_(another.t()), reactants_(another.reactants()), + products_(another.products()) + { + } + + Real t() const { return t_; } + + bool has_occurred() const + { + return reactants_.size() > 0 || products_.size() > 0; + } + + const container_type &reactants() const { return reactants_; } + + void add_reactant(const Item &item) { reactants_.push_back(item); } + + const container_type &products() const { return products_; } + + void add_product(const Item &item) { products_.push_back(item); } + +protected: + Real t_; + container_type reactants_, products_; +}; + +// Application of reactions + +class SpatiocyteWorld; + +ReactionInfo apply_a2b(std::shared_ptr world, + const ReactionInfo::Item &reactant_item, + const Species &product_species); + +ReactionInfo apply_a2bc(std::shared_ptr world, + const ReactionInfo::Item &reactant_item, + const Species &product_species0, + const Species &product_species1); + +ReactionInfo +apply_second_order_reaction(std::shared_ptr world, + const ReactionRule &reaction_rule, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1); + +ReactionInfo apply_vanishment(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1); + +ReactionInfo apply_ab2c(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1, + const Species &product_species); + +ReactionInfo apply_ab2cd(std::shared_ptr world, + const ReactionInfo::Item &reactant_item0, + const ReactionInfo::Item &reactant_item1, + const Species &product_species0, + const Species &product_species1); + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_SPATIOCYTE_REACTIONS_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/ReactionEvent.cpp",".cpp","3637","141","#include ""SpatiocyteEvent.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +/// ZerothOrderReactionEvent + +ZerothOrderReactionEvent::ZerothOrderReactionEvent( + std::shared_ptr world, const ReactionRule &rule, + const Real &t) + : SpatiocyteEvent(t), world_(world), rule_(rule) +{ + time_ = t + draw_dt(); +} + +void ZerothOrderReactionEvent::fire_() +{ + ReactionInfo rinfo(world_->t()); + + for (const auto &sp : rule_.products()) + { + const MoleculeInfo info(world_->get_molecule_info(sp)); + + if (const auto space_and_location = + world_->find_space_and_voxel_pool(Species(info.loc))) + { + const auto space = space_and_location->first; + const auto location = space_and_location->second; + + if (location->size() == 0) + { + time_ += draw_dt(); + return; + } + + while (true) + { + const Voxel voxel( + space, world_->rng()->uniform_int(0, space->size() - 1)); + + if (voxel.get_voxel_pool() != location) + { + continue; + } + + if (boost::optional pid = + world_->new_particle(sp, voxel)) + { + rinfo.add_product(ReactionInfo::Item(*pid, sp, voxel)); + break; + } + } + } + } + push_reaction(std::make_pair(rule_, rinfo)); + time_ += draw_dt(); +} + +Real ZerothOrderReactionEvent::draw_dt() +{ + const Real k(rule_.k()); + const Real p = k * world_->volume(); + Real dt(std::numeric_limits::infinity()); + if (p != 0.) + { + const Real rnd(world_->rng()->uniform(0., 1.)); + dt = -log(1 - rnd) / p; + } + return dt; +} + +/// FirstOrderReactionEvent + +FirstOrderReactionEvent::FirstOrderReactionEvent( + std::shared_ptr world, const ReactionRule &rule, + const Real &t) + : SpatiocyteEvent(t), world_(world), rng_(world->rng()), rule_(rule) +{ + // assert(rule_.reactants().size() == 1); + time_ = t + draw_dt(); +} + +void FirstOrderReactionEvent::fire_() +{ + const ReactionInfo::Item reactant_item(choice()); + const ReactionRule::product_container_type &products(rule_.products()); + + switch (products.size()) + { + case 0: { + reactant_item.voxel.clear(); + ReactionInfo rinfo(world_->t()); + rinfo.add_reactant(reactant_item); + push_reaction(std::make_pair(rule_, rinfo)); + } + break; + case 1: + push_reaction(std::make_pair( + rule_, apply_a2b(world_, reactant_item, *(products.begin())))); + break; + case 2: { + ReactionInfo rinfo(apply_a2bc(world_, reactant_item, + *(products.begin()), + (*(++products.begin())))); + if (rinfo.has_occurred()) + push_reaction(std::make_pair(rule_, rinfo)); + } + break; + } + time_ += draw_dt(); +} + +Real FirstOrderReactionEvent::draw_dt() +{ + const Species &reactant(*(rule_.reactants().begin())); + const Integer num_r(world_->num_voxels_exact(reactant)); + const Real k(rule_.k()); + if (num_r > 0) + { + const Real p = k * num_r; + Real dt(std::numeric_limits::infinity()); + if (p != 0.) + { + const Real rnd(world_->rng()->uniform(0., 1.)); + dt = -log(1 - rnd) / p; + } + return dt; + } + else + { + return std::numeric_limits::infinity(); + } +} + +} // namespace spatiocyte + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteSimulator.cpp",".cpp","6371","226","#include ""SpatiocyteSimulator.hpp"" +#include ""utils.hpp"" + +#include +#include +#include + +namespace ecell4 +{ + +namespace spatiocyte +{ + +void SpatiocyteSimulator::initialize() +{ + last_reactions_.clear(); + species_list_.clear(); // XXX:FIXME: Messy patch + + scheduler_.clear(); + update_alpha_map(); + for (const auto &species : world_->list_species()) + { + register_events(species); + } + + for (const auto &rule : model_->reaction_rules()) + { + if (rule.reactants().size() != 0) + { + continue; + } + const std::shared_ptr zeroth_order_reaction_event( + create_zeroth_order_reaction_event(rule, world_->t())); + scheduler_.add(zeroth_order_reaction_event); + } + + dt_ = scheduler_.next_time() - t(); +} + +void SpatiocyteSimulator::update_alpha_map() +{ + std::shared_ptr model_(model()); + if (!model_ || !model_->is_static()) + return; + + for (const auto &rule : model_->reaction_rules()) + { + const ReactionRule::reactant_container_type &reactants( + rule.reactants()); + if (reactants.size() != 2) + continue; + + const Real alpha(calculate_alpha(rule, world_)); + for (int i(0); i < 2; ++i) + { + const Species &sp(reactants.at(i)); + alpha_map_type::iterator map_itr(alpha_map_.find(sp)); + if (map_itr == alpha_map_.end()) + alpha_map_.insert(alpha_map_type::value_type(sp, alpha)); + else if ((*map_itr).second > alpha) + (*map_itr).second = alpha; + } + } +} + +void SpatiocyteSimulator::register_events(const Species &sp) +{ + species_list_.push_back(sp); // XXX:FIXME: Messy patch + + if (world_->has_molecule_pool(sp)) + { + // TODO: Call steps only if sp is assigned not to StructureType. + alpha_map_type::const_iterator itr(alpha_map_.find(sp)); + const Real alpha(itr != alpha_map_.end() ? itr->second : 1.0); + const std::shared_ptr step_event( + create_step_event(sp, world_->t(), alpha)); + scheduler_.add(step_event); + } + + for (const auto &rule : model_->query_reaction_rules(sp)) + { + const std::shared_ptr first_order_reaction_event( + create_first_order_reaction_event(rule, world_->t())); + scheduler_.add(first_order_reaction_event); + } +} + +std::shared_ptr +SpatiocyteSimulator::create_step_event(const Species &species, const Real &t, + const Real &alpha) +{ + std::shared_ptr mpool(world_->find_molecule_pool(species)); + const Shape::dimension_kind dimension(world_->get_dimension(species)); + + if (dimension == Shape::THREE) + { + return std::shared_ptr( + new StepEvent<3>(model_, world_, species, t, alpha)); + } + else if (dimension == Shape::TWO) + { + return std::shared_ptr( + new StepEvent<2>(model_, world_, species, t, alpha)); + } + else + { + throw NotSupported( + ""The dimension of a structure must be two or three.""); + } +} + +std::shared_ptr +SpatiocyteSimulator::create_zeroth_order_reaction_event( + const ReactionRule &reaction_rule, const Real &t) +{ + std::shared_ptr event( + new ZerothOrderReactionEvent(world_, reaction_rule, t)); + return event; +} + +std::shared_ptr +SpatiocyteSimulator::create_first_order_reaction_event( + const ReactionRule &reaction_rule, const Real &t) +{ + std::shared_ptr event( + new FirstOrderReactionEvent(world_, reaction_rule, t)); + return event; +} + +void SpatiocyteSimulator::finalize() +{ + for (const auto &item : scheduler_.events()) + { + const auto &event(item.second); + const Real queued_time(event->time() - event->dt()); + auto *step3_event(dynamic_cast *>(event.get())); + if (step3_event != NULL && queued_time < t()) + { + const Real factor((t() - queued_time) / event->dt()); + // assert(factor <= 1); + step3_event->walk(step3_event->alpha() * factor); + } + auto *step2_event(dynamic_cast *>(event.get())); + if (step2_event != NULL && queued_time < t()) + { + const Real factor((t() - queued_time) / event->dt()); + // assert(factor <= 1); + step2_event->walk(step2_event->alpha() * factor); + } + } + + initialize(); +} + +void SpatiocyteSimulator::step() +{ + step_(); + dt_ = scheduler_.next_time() - t(); +} + +bool SpatiocyteSimulator::step(const Real &upto) +{ + if (upto < t()) + { + return false; + } + + if (scheduler_.size() > 0 && upto >= scheduler_.top().second->time()) + { + step_(); + dt_ = scheduler_.next_time() - t(); + return true; + } + + world_->set_t(upto); + last_reactions_.clear(); + dt_ = scheduler_.next_time() - t(); + finalize(); + return false; +} + +void SpatiocyteSimulator::step_() +{ + scheduler_type::value_type top(scheduler_.pop()); + const Real time(top.second->time()); + world_->set_t(time); + top.second->fire(); // top.second->time_ is updated in fire() + set_last_event_( + std::const_pointer_cast(top.second)); + + last_reactions_ = last_event_->reactions(); + + std::vector new_species; + for (const auto &reaction : last_reactions()) + { + for (const auto &product : reaction.second.products()) + { + const Species &species(product.species); + // if (!world_->has_species(species)) + if (std::find(species_list_.begin(), species_list_.end(), + species) == + species_list_.end()) // XXX:FIXME: Messy patch + new_species.push_back(species); + } + } + + for (const auto &event : scheduler_.events()) + { + event.second->interrupt(time); + scheduler_.update(event); + } + scheduler_.add(top.second); + + // update_alpha_map(); // may be performance cost + for (const auto &species : new_species) + { + register_events(species); + } + + num_steps_++; +} + +} // namespace spatiocyte + +} // namespace ecell4 +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/SpatiocyteWorld.hpp",".hpp","31207","1005","#ifndef ECELL4_LATTICE_LATTICE_WORLD_HPP +#define ECELL4_LATTICE_LATTICE_WORLD_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include ""OneToManyMap.hpp"" +#include ""SpatiocyteReactions.hpp"" +#include ""Voxel.hpp"" + +namespace ecell4 +{ + +namespace spatiocyte +{ + +struct MoleculeInfo +{ + Real radius; + Real D; + std::string loc; + Shape::dimension_kind dimension; +}; + +class SpatiocyteWorld : public WorldInterface +{ +public: + typedef LatticeSpaceVectorImpl default_root_type; + + typedef VoxelSpaceBase::coordinate_id_pair_type coordinate_id_pair_type; + + typedef std::shared_ptr space_type; + typedef std::vector space_container_type; + +public: + /* + * Constructors + */ + SpatiocyteWorld(const Real3 &edge_lengths, const Real &voxel_radius, + const std::shared_ptr &rng) + : rng_(rng) + { + spaces_.push_back( + space_type(new default_root_type(edge_lengths, voxel_radius))); + size_ = get_root()->size(); + } + + SpatiocyteWorld(const Real3 &edge_lengths, const Real &voxel_radius) + { + spaces_.push_back( + space_type(new default_root_type(edge_lengths, voxel_radius))); + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); + size_ = get_root()->size(); + } + + SpatiocyteWorld(const Real3 &edge_lengths = Real3(1, 1, 1)) + { + // XXX: sloppy default + spaces_.push_back(space_type( + new default_root_type(edge_lengths, edge_lengths[0] / 100))); + size_ = get_root()->size(); + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + (*rng_).seed(); + } + + SpatiocyteWorld(const std::string filename) + { + // XXX: sloppy default + spaces_.push_back( + space_type(new default_root_type(Real3(1, 1, 1), 1 / 100))); + rng_ = std::shared_ptr( + new GSLRandomNumberGenerator()); + this->load(filename); + } + + SpatiocyteWorld(VoxelSpaceBase *space, + const std::shared_ptr &rng) + : rng_(rng) + { + spaces_.push_back(space_type(space)); + size_ = get_root()->size(); + } + + void add_space(std::unique_ptr space); + + const Real t() const + { + Real time(0.0); + + for (const auto &space : spaces_) + { + time = std::max(time, space->t()); + } + + return time; + } + + void set_t(const Real &t) + { + for (auto &space : spaces_) + { + space->set_t(t); + } + } + + void save(const std::string &filename) const + { +#ifdef WITH_HDF5 + std::unique_ptr fout( + new H5::H5File(filename.c_str(), H5F_ACC_TRUNC)); + rng_->save(fout.get()); + sidgen_.save(fout.get()); + std::unique_ptr group( + new H5::Group(fout->createGroup(""LatticeSpace""))); + get_root()->save_hdf5(group.get()); // TODO + extras::save_version_information(fout.get(), + std::string(""ecell4-spatiocyte-"") + + std::string(VERSION_INFO)); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + void load(const std::string &filename) + { +#ifdef WITH_HDF5 + std::unique_ptr fin( + new H5::H5File(filename.c_str(), H5F_ACC_RDONLY)); + + const std::string required = ""ecell4-spatiocyte-0.0""; + try + { + const std::string version = extras::load_version_information(*fin); + if (!extras::check_version_information(version, required)) + { + std::stringstream ss; + ss << ""The version of the given file ["" << version + << ""] is too old. ["" << required + << ""] or later is required.""; + throw NotSupported(ss.str()); + } + } + catch (H5::GroupIException not_found_error) + { + throw NotFound(""No version information was found.""); + } + + const H5::Group group(fin->openGroup(""LatticeSpace"")); + get_root()->load_hdf5(group); // TODO + sidgen_.load(*fin); + rng_->load(*fin); +#else + throw NotSupported( + ""This method requires HDF5. The HDF5 support is turned off.""); +#endif + } + + // Integer num_species() const + // { + // Integer total(0); + // for (space_container_type::const_iterator itr(spaces_.begin()); + // itr != spaces_.end(); ++itr) + // { + // total += (*itr)->num_species(); + // } + // return total; + // } + + bool has_species(const Species &sp) const + { + for (const auto &space : spaces_) + { + if (space->has_species(sp)) + return true; + } + return false; + } + + Integer num_molecules(const Species &sp) const + { + Integer total(0); + for (const auto &space : spaces_) + { + total += space->num_molecules(sp); + } + return total; + } + + Integer num_molecules_exact(const Species &sp) const + { + Integer total(0); + for (const auto &space : spaces_) + { + total += space->num_molecules_exact(sp); + } + return total; + } + + Real get_value(const Species &sp) const + { + return static_cast(num_molecules(sp)); + } + + Real get_value_exact(const Species &sp) const + { + return static_cast(num_molecules_exact(sp)); + } + + const Real3 &edge_lengths() const { return get_root()->edge_lengths(); } + + Integer num_particles() const { return num_voxels(); } + + Integer num_particles(const Species &sp) const { return num_voxels(sp); } + + Integer num_particles_exact(const Species &sp) const + { + return num_voxels_exact(sp); + } + + boost::optional get_voxel(const ParticleID &pid) const + { + for (const auto &space : spaces_) + { + if (const auto coordinate = space->get_coordinate(pid)) + return Voxel(space, *coordinate); + } + return boost::none; + } + + bool has_particle(const ParticleID &pid) const { return has_voxel(pid); } + + // Suggests: Rename to 'find_particle' + std::pair get_particle(const ParticleID &pid) const + { + for (const auto &space : spaces_) + { + if (const auto &view = space->find_voxel(pid)) + { + return std::make_pair(pid, gen_particle_from(space, *view)); + } + } + throw ""No particle corresponding to a given ParticleID is found.""; + } + + std::vector> list_particles() const + { + return list_particles_private( + [](const space_type &space) { return space->list_voxels(); }); + } + + std::vector> + list_particles(const Species &sp) const + { + return list_particles_private( + [&sp](const space_type &space) { return space->list_voxels(sp); }); + } + + std::vector> + list_particles_exact(const Species &sp) const + { + return list_particles_private([&sp](const space_type &space) { + return space->list_voxels_exact(sp); + }); + } + + std::vector> + list_structure_particles() const; + std::vector> + list_non_structure_particles() const; + + Real voxel_radius() const { return get_root()->voxel_radius(); } + + Real voxel_volume() const { return get_root()->voxel_volume(); } + + Real get_volume(const Species &sp) const + { + for (const auto &space : spaces_) + { + if (space->has_species(sp) && + space->find_molecule_pool(sp)->is_structure()) + return space->get_volume(sp); + } + return 0.0; + } + + const Real volume() const { return get_root()->volume(); } + + Real unit_area() const { return get_root()->unit_area(); } + + // TODO + std::shared_ptr vacant() const { return get_root()->vacant(); } + + bool has_voxel(const ParticleID &pid) const + { + for (const auto &space : spaces_) + { + if (space->has_voxel(pid)) + return true; + } + return false; + } + + Integer num_voxels() const + { + Integer total(0); + for (const auto &space : spaces_) + { + total += space->num_voxels(); + } + return total; + } + + Integer num_voxels(const Species &sp) const + { + Integer total(0); + for (const auto &space : spaces_) + { + total += space->num_voxels(sp); + } + return total; + } + + Integer num_voxels_exact(const Species &sp) const + { + Integer total(0); + for (const auto &space : spaces_) + { + total += space->num_voxels_exact(sp); + } + return total; + } + + std::vector> list_voxels() const + { + return list_voxels_private( + [](const space_type &space) { return space->list_voxels(); }); + } + + std::vector> list_voxels(const Species &sp) const + { + return list_voxels_private( + [&sp](const space_type &space) { return space->list_voxels(sp); }); + } + + std::vector> list_voxels_exact(const Species &sp) const + { + return list_voxels_private([&sp](const space_type &space) { + return space->list_voxels_exact(sp); + }); + } + + Species get_species_at(const Voxel &voxel) const + { + return voxel.get_voxel_pool()->species(); + } + + bool has_particle_at(const Voxel &voxel) const + { + return !voxel.get_voxel_pool()->is_vacant(); + } + + std::pair get_voxel_at(const Voxel &voxel) const + { + const auto view(voxel.space.lock()->get_voxel_at(voxel.coordinate)); + return std::make_pair(view.pid, view.species); + } + + std::shared_ptr find_voxel_pool(const Species &species) + { + for (const auto &space : spaces_) + { + if (space->has_species(species)) + return space->find_voxel_pool(species); + } + // create VoxelPool TODO + return get_root()->find_voxel_pool(species); + // throw ""No VoxelPool corresponding to a given Species is found""; + } + + std::shared_ptr + find_voxel_pool(const Species &species) const + { + for (const auto &space : spaces_) + { + if (space->has_species(species)) + return space->find_voxel_pool(species); + } + throw ""No VoxelPool corresponding to a given Species is found""; + } + + boost::optional>> + find_space_and_voxel_pool(const Species &species) const + { + for (const auto &space : spaces_) + { + if (space->has_species(species)) + { + const auto voxel_pool = space->find_voxel_pool(species); + return std::pair>( + space, voxel_pool); + } + } + return boost::none; + } + + bool has_molecule_pool(const Species &species) const + { + for (const auto &space : spaces_) + { + if (space->has_molecule_pool(species)) + return true; + } + return false; + } + + std::shared_ptr find_molecule_pool(const Species &species) + { + for (const auto &space : spaces_) + { + if (space->has_molecule_pool(species)) + return space->find_molecule_pool(species); + } + throw ""No MoleculePool corresponding to a given Species is found""; + } + + std::shared_ptr + find_molecule_pool(const Species &species) const + { + for (const auto &space : spaces_) + { + if (space->has_molecule_pool(species)) + return space->find_molecule_pool(species); + } + throw ""No MoleculePool corresponding to a given Species is found""; + } + + boost::optional>> + find_space_and_molecule_pool(const Species &species) const + { + for (const auto &space : spaces_) + { + if (space->has_molecule_pool(species)) + { + const auto molecule_pool(space->find_molecule_pool(species)); + return std::pair>( + space, molecule_pool); + } + } + return boost::none; + } + + /* + * Coordinate Transformation + */ + Voxel get_voxel_nearby(const Real3 &pos) const + { + return Voxel(get_root(), get_root()->position2coordinate(pos)); + } + + /* + * Voxel Manipulation + */ + bool update_voxel(const ParticleID &pid, const Species species, + const Voxel voxel) + { + const MoleculeInfo minfo(get_molecule_info(species)); + + const auto target_space = voxel.space.lock(); + for (const auto &space : spaces_) + { + if (space->has_voxel(pid)) + { + if (space != target_space) + { + space->remove_voxel(pid); + } + return target_space->update_voxel(pid, species, + voxel.coordinate); + } + } + + if (!target_space->has_species(species)) + { + target_space->make_molecular_type(species, minfo.loc); + } + return target_space->update_voxel(pid, species, voxel.coordinate); + } + + bool remove_voxel(const ParticleID &pid) + { + for (const auto &space : spaces_) + { + if (space->has_voxel(pid)) + return space->remove_voxel(pid); + } + return false; + } + + // Deprecated + bool can_move(const Voxel &src, const Voxel &dst) const + { + // if they share the ownership (or both are empty), then we can move it. + // owner_before compares not only the number of owners, but also the + // address itself. + if (!src.space.owner_before(dst.space) && !dst.space.owner_before(src.space)) + { + return src.space.lock()->can_move(src.coordinate, dst.coordinate); + } + return false; + } + + // Deprecated + bool move(const Voxel &src, const Voxel &dst, + const std::size_t candidate = 0) + { + // if they share the ownership (or both are empty), then we can move it. + // owner_before compares not only the number of owners, but also the + // address itself. + if (!src.space.owner_before(dst.space) && !dst.space.owner_before(src.space)) + { + return src.space.lock()->move(src.coordinate, dst.coordinate, + candidate); + } + return false; + } + + const Integer size() const { return size_; } + + const Integer3 shape() const { return get_root()->shape(); } + + /* + * SpatiocyteWorld API + */ + + const MoleculeInfo get_molecule_info(const Species &sp) const + { + const auto itr = molecule_info_cache_.find(sp); + if (itr != molecule_info_cache_.end()) + { + return itr->second; + } + throw NotFound(""MoleculeInfo not found""); + } + + /** + * draw attributes of species and return it as a molecule info. + * @param sp a species + * @return info a molecule info + */ + const MoleculeInfo get_molecule_info(const Species &sp) + { + // Default + MoleculeInfo info = { + /* radius = */ voxel_radius(), + /* D = */ 0.0, + /* loc = */ """", + /* dimension = */ Shape::THREE, + }; + + const auto itr = molecule_info_cache_.find(sp); + if (itr != molecule_info_cache_.end()) + { + // return itr->second; + // TODO: the below code is only for warning. + // In the future, the value should be returned immediately. + info = itr->second; + } + else if (const auto model = lock_model()) + { + const auto species_from_model(model->apply_species_attributes(sp)); + + if (species_from_model.has_attribute(""D"")) + { + info.D = species_from_model.get_attribute_as(""D""); + } + + if (species_from_model.has_attribute(""radius"")) + { + info.radius = + species_from_model.get_attribute_as(""radius""); + } + + if (species_from_model.has_attribute(""location"")) + { + info.loc = species_from_model.get_attribute_as( + ""location""); + } + + info.dimension = extras::get_dimension_from_model(sp, model); + } + + if (sp.has_attribute(""D"")) + { + const auto new_value = sp.get_attribute_as(""D""); + if (info.D != new_value) + { + warning(""D""); + info.D = new_value; + } + } + + if (sp.has_attribute(""radius"")) + { + const auto new_value = sp.get_attribute_as(""radius""); + if (info.radius != new_value) + { + warning(""radius""); + info.radius = new_value; + } + } + + if (sp.has_attribute(""location"")) + { + const auto new_value = sp.get_attribute_as(""location""); + if (info.loc != new_value) + { + warning(""location""); + info.loc = new_value; + } + } + + molecule_info_cache_.insert( + molecule_info_cache_t::value_type(sp, info)); + return info; + } + + static inline void warning(const std::string attribute) + { + std::cerr << ""Warning: A given species has an attribute \"""" << attribute + << ""\""""; + std::cerr << "", but its value differs from that of the bound Model or "" + ""the value previously given."" + << std::endl; + std::cerr << "" Giving the different value from a species "" + ""attribute are deprecated."" + << std::endl; + std::cerr << "" An attribute of a given species will be ignored "" + ""in the future."" + << std::endl; + } + + // bool has_species_exact(const Species &sp) const + // { + // return get_root()->has_species_exact(sp); + // } + + void set_value(const Species &sp, const Real value); + + /** + * create and add a new particle + * @param p a particle + * @return a pair of a pair of pid (a particle id) and p (a particle) + * and bool (if it's succeeded or not) + */ + boost::optional new_particle(const Particle &p) + { + // ParticleID pid(sidgen_()); + // const bool is_succeeded(update_particle(pid, p)); + // return std::make_pair(get_particle(pid), is_succeeded); + const MoleculeInfo minfo(get_molecule_info(p.species())); + const Voxel voxel(get_voxel_nearby(p.position())); + + if (voxel.get_voxel_pool()->species().serial() != minfo.loc) + return boost::none; + + if (boost::optional pid = new_particle(p.species(), voxel)) + return *pid; + + return boost::none; + } + + boost::optional new_particle(const Species &sp, + const Real3 &pos) + { + const MoleculeInfo info(get_molecule_info(sp)); + return new_particle(Particle(sp, pos, info.radius, info.D)); + } + + bool remove_particle(const ParticleID &pid) { return remove_voxel(pid); } + + bool update_particle(const ParticleID &pid, const Particle &p) + { + const MoleculeInfo minfo(get_molecule_info(p.species())); + return update_voxel(pid, p.species(), get_voxel_nearby(p.position())); + } + + std::vector list_species() const + { + std::vector list; + for (const auto &space : spaces_) + { + std::vector species(space->list_species()); + list.insert(list.end(), species.begin(), species.end()); + } + return list; + } + + std::vector list_non_structure_species() const; + std::vector list_structure_species() const; + + boost::optional new_particle(const Species &sp, + const Voxel &voxel) + { + std::shared_ptr space(voxel.space.lock()); + if (!space->has_species(sp)) + { + const MoleculeInfo minfo(get_molecule_info(sp)); + space->make_molecular_type(sp, minfo.loc); + } + + ParticleID pid(sidgen_()); + + if (space->add_voxel(sp, pid, voxel.coordinate)) + return pid; + + return boost::none; + } + + boost::optional new_voxel_structure(const Species &sp, + const Voxel &voxel) + { + std::shared_ptr space(voxel.space.lock()); + if (!space->has_species(sp)) + { + const MoleculeInfo minfo(get_molecule_info(sp)); + space->make_structure_type(sp, minfo.loc); + } + + ParticleID pid; + + if (space->add_voxel(sp, pid, voxel.coordinate)) + return pid; + + return boost::none; + } + + bool add_molecules(const Species &sp, const Integer &num); + bool add_molecules(const Species &sp, const Integer &num, + const std::shared_ptr shape); + Integer add_structure(const Species &sp, + const std::shared_ptr shape); + + void remove_molecules(const Species &sp, const Integer &num); + // void remove_molecules_exact(const Species& sp, const Integer& num); + + boost::optional check_neighbor(const Voxel &voxel, + const std::string &loc); + + const Integer num_neighbors(const Voxel &voxel) const + { + return voxel.space.lock()->num_neighbors(voxel.coordinate); + } + + const Voxel get_neighbor(const Voxel &voxel, Integer nrand) const + { + return Voxel(voxel.space, + voxel.space.lock()->get_neighbor(voxel.coordinate, nrand)); + } + + template + const Voxel get_neighbor_randomly(const Voxel &voxel); + + const Species &draw_species(const Species &pttrn) const; + + std::shared_ptr rng() const { return rng_; } + + void bind_to(std::shared_ptr model) + { + if (std::shared_ptr bound_model = model_.lock()) + { + if (bound_model.get() != model.get()) + { + std::cerr << ""Warning: Model already bound to SpatiocyteWorld"" + << std::endl; + } + } + + model_ = model; + } + + std::shared_ptr lock_model() const + { + const auto bound = model_.lock(); + if (!bound) + { + std::cerr << ""Warning: Manipulating SpatiocyteWorld without "" + ""binding Model is deprecated."" + << std::endl; + std::cerr << "" In the future, calling this function before "" + ""binding Model will throw an exception."" + << std::endl; + } + return bound; + } + + Shape::dimension_kind get_dimension(const Species &species) + { + return get_molecule_info(species).dimension; + } + + Shape::dimension_kind get_dimension(const Species &species) const + { + return get_molecule_info(species).dimension; + } + + /** + * static members + */ + static inline Real calculate_voxel_volume(const Real r) + { + return VoxelSpaceBase::calculate_voxel_volume(r); + } + + static inline Real3 calculate_hcp_lengths(const Real voxel_radius) + { + return VoxelSpaceBase::calculate_hcp_lengths(voxel_radius); + } + + static inline Integer3 calculate_shape(const Real3 &edge_lengths, + const Real &voxel_radius) + { + return VoxelSpaceBase::calculate_shape(edge_lengths, voxel_radius, + true); + } + + static inline Real calculate_volume(const Real3 &edge_lengths, + const Real &voxel_radius) + { + return VoxelSpaceBase::calculate_volume(edge_lengths, voxel_radius, + true); + } + +protected: + space_type get_root() const { return spaces_.at(0); } + + Integer add_structure2(const Species &sp, const std::string &location, + const std::shared_ptr shape); + Integer add_structure3(const Species &sp, const std::string &location, + const std::shared_ptr shape); + bool is_surface_voxel(const Voxel &voxel, + const std::shared_ptr shape) const; + + Particle gen_particle_from(const space_type &space, + const VoxelView &view) const + { + const auto species = view.species; + + const auto position = space->coordinate2position(view.voxel); + const auto minfo_iter = molecule_info_cache_.find(species); + if (minfo_iter != molecule_info_cache_.end()) + { + const auto &minfo = minfo_iter->second; + return Particle(species, position, minfo.radius, minfo.D, + minfo.loc); + } + else + { + return Particle(species, position, 0.0, 0.0, """"); + } + } + +private: + template + std::vector map_voxels(ListFn list_f, Fn f) const + { + std::vector list; + for (const auto &space : spaces_) + { + const auto voxels(list_f(space)); + list.reserve(list.size() + voxels.size()); + for (const auto &item : voxels) + { + list.push_back(f(space, item)); + } + } + return list; + } + + template + std::vector> + list_particles_private(ListFn list_fn) const + { + return map_voxels>( + list_fn, [this](const space_type &space, const VoxelView &view) { + return std::make_pair(view.pid, gen_particle_from(space, view)); + }); + } + + template + std::vector> list_voxels_private(ListFn list_fn) const + { + return map_voxels>( + list_fn, [this](const space_type &space, const VoxelView &view) { + return ParticleBase(view.pid, view.species, + Voxel(space, view.voxel)); + }); + } + +protected: + typedef std::unordered_map + molecule_info_cache_t; + + std::size_t size_; + space_container_type spaces_; + + OneToManyMap interfaces_; + OneToManyMap neighbors_; + + std::shared_ptr rng_; + SerialIDGenerator sidgen_; + + std::weak_ptr model_; + molecule_info_cache_t molecule_info_cache_; +}; // namespace spatiocyte + +inline SpatiocyteWorld *create_spatiocyte_world_cell_list_impl( + const Real3 &edge_lengths, const Real &voxel_radius, + const Integer3 &matrix_sizes, + const std::shared_ptr &rng) +{ + return new SpatiocyteWorld( + new LatticeSpaceCellListImpl(edge_lengths, voxel_radius, matrix_sizes), + rng); +} + +inline SpatiocyteWorld *create_spatiocyte_world_vector_impl( + const Real3 &edge_lengths, const Real &voxel_radius, + const std::shared_ptr &rng) +{ + return new SpatiocyteWorld( + new LatticeSpaceVectorImpl(edge_lengths, voxel_radius), rng); +} + +inline SpatiocyteWorld *allocate_spatiocyte_world_square_offlattice_impl( + const Real edge_length, const Species &species, const Real &voxel_radius, + const std::shared_ptr &rng) +{ + OffLatticeSpace::position_container positions; + OffLatticeSpace::coordinate_pair_list_type adjoining_pairs; + + // const std::size_t num_row(int((edge_length - (2 + sqrt(3)) * + // voxel_radius) / + // (2 * sqrt(3) * voxel_radius)) + 1); + const std::size_t num_row(int(edge_length / (2 * sqrt(3) * voxel_radius))); + const std::size_t num_col(int(edge_length / (2 * voxel_radius))); + + for (std::size_t row(0); row < num_row; ++row) + for (std::size_t col(0); col < num_col; ++col) + { + // 2 * (row * num_col + col) + positions.push_back(Real3(2 * col, 2 * row * sqrt(3), 0) * + voxel_radius); + + // 2 * (row * num_col + col + 1) + positions.push_back(Real3(2 * col, (2 * row + 1) * sqrt(3), 0) * + voxel_radius); + + const int index(2 * (row * num_col + col)); + + const std::size_t next_col((col + 1) % num_col); + const std::size_t next_row((row + 1) % num_row); + + const int right(2 * (row * num_col + next_col)); + const int bottom(2 * (next_row * num_col + col)); + const int right_bottom(2 * (next_row * num_col + next_col)); + + adjoining_pairs.push_back(std::make_pair(index, index + 1)); + adjoining_pairs.push_back(std::make_pair(index, right)); + adjoining_pairs.push_back(std::make_pair(index + 1, right)); + adjoining_pairs.push_back(std::make_pair(index + 1, right + 1)); + adjoining_pairs.push_back(std::make_pair(index + 1, bottom)); + adjoining_pairs.push_back(std::make_pair(index + 1, right_bottom)); + } + + OffLatticeSpace *space = + new OffLatticeSpace(voxel_radius, species, positions, adjoining_pairs); + space->set_lengths(Real3(2 * num_col, 2 * sqrt(3) * num_row, 2) * + voxel_radius); + + return new SpatiocyteWorld(space, rng); +} + +} // namespace spatiocyte + +} // namespace ecell4 + +#endif /* ECELL4_LATTICE_LATTICE_WORLD_HPP */ +","Unknown" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/samples/simple_lattice.cpp",".cpp","2171","79","#include + +#include +#include +#include + +#include +typedef ecell4::spatiocyte::SpatiocyteWorld world_type; +typedef ecell4::spatiocyte::SpatiocyteSimulator simulator_type; + +namespace ecell4 +{ + +void run() +{ + const Real world_size(1e-6); + const Real3 edge_lengths(world_size, world_size, world_size); + const Real volume(world_size * world_size * world_size); + const Real voxel_radius(2.5e-9); + + const Integer N(60); + + const Real D(1e-12), radius(2.5e-9); + + //const Real kd(0.1), U(0.5); + const Real kd(0.5), U(0.5); + const Real ka(kd * volume * (1 - U) / (U * U * N)); + + Species sp1(""A"", radius, D), sp2(""B"", radius, D), sp3(""C"", radius, D); + ReactionRule rr1(create_unbinding_reaction_rule(sp1, sp2, sp3, kd)), + rr2(create_binding_reaction_rule(sp2, sp3, sp1, ka)); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + model->add_reaction_rule(rr1); + model->add_reaction_rule(rr2); + + std::shared_ptr + rng(new GSLRandomNumberGenerator()); + rng->seed(time(NULL)); + + std::shared_ptr world( + new world_type(edge_lengths, voxel_radius, rng)); + + world->add_molecules(sp1, N); + + simulator_type sim(world, model); + + Real next_time(0.0), dt(0.02); + std::cout << sim.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + for (unsigned int i(0); i < 100; ++i) + { + next_time += dt; + while (sim.step(next_time)) {} + + std::cout << sim.t() + << ""\t"" << world->num_molecules(sp1) + << ""\t"" << world->num_molecules(sp2) + << ""\t"" << world->num_molecules(sp3) + << std::endl; + } +} + +} // ecell4 + +/** + * main function + */ +int main(int argc, char** argv) +{ + ecell4::run(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/samples/diffusion.cpp",".cpp","1573","62","#include + +#include +#include +#include + +#include +#include +typedef ecell4::spatiocyte::SpatiocyteWorld world_type; +typedef ecell4::spatiocyte::SpatiocyteSimulator simulator_type; + +namespace ecell4 +{ + +void run() +{ + const Real world_size(1); + const Real3 edge_lengths(world_size, world_size, world_size); + const Real voxel_radius(0.0025); + + const Integer N(60); + + const Real D(1.0), radius(0.0025); + + Species sp(""A"", radius, D); + + std::shared_ptr model(new NetworkModel()); + std::shared_ptr + rng(new GSLRandomNumberGenerator()); + rng->seed(0); + // rng->seed(time(NULL)); + + // std::shared_ptr world( + // new world_type(edge_lengths, voxel_radius, rng)); + // std::shared_ptr world( + // create_spatiocyte_world_vector_impl(edge_lengths, voxel_radius, rng)); + std::shared_ptr world( + ecell4::spatiocyte::create_spatiocyte_world_cell_list_impl( + edge_lengths, voxel_radius, Integer3(5, 5, 5), rng)); + + world->add_molecules(sp, N); + + simulator_type sim(world, model); + std::cout << ""dt = "" << sim.dt() << std::endl; + for (unsigned int i(0); i != 1000; ++i) + { + sim.step(); + } + + // while (sim.step(1.0)) ; // do nothing +} + +} // ecell4 + +/** + * main function + */ +int main(int argc, char** argv) +{ + ecell4::run(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/tests/OneToManyMap_test.cpp",".cpp","1162","52","#define BOOST_TEST_MODULE ""OneToManyMap_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +# include +#else +# define BOOST_TEST_NO_LIB +# include +#endif + +#include + +#include ""../OneToManyMap.hpp"" + +using namespace ecell4; +using namespace ecell4::spatiocyte; + +BOOST_AUTO_TEST_CASE( Constructor ) +{ + OneToManyMap container; +} + +BOOST_AUTO_TEST_CASE( AddInterface ) +{ + OneToManyMap container; + + container.add(0, 3); + boost::optional&> values(container.find(0)); + + BOOST_ASSERT( values ); + BOOST_CHECK_EQUAL( 1, values->size() ); + BOOST_CHECK_EQUAL( 3, values->at(0) ); + + container.add(0, 5); + BOOST_CHECK_EQUAL( 2, values->size() ); + + values = container.find(0); + BOOST_ASSERT( values ); + BOOST_CHECK_EQUAL( 2, values->size() ); + BOOST_CHECK_EQUAL( 3, values->at(0) ); + BOOST_CHECK_EQUAL( 5, values->at(1) ); +} + +BOOST_AUTO_TEST_CASE( GET ) +{ + OneToManyMap container; + + container.add(0, 1); + + BOOST_CHECK( container.find(0) ); + BOOST_CHECK( !container.find(1) ); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/tests/SpatiocyteWorld_test.cpp",".cpp","7472","256","#define BOOST_TEST_MODULE ""SpatiocyteWorld_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +#include +#else +#define BOOST_TEST_NO_LIB +#include +#endif + +#include + +#include ""../OffLattice.hpp"" +#include ""../SpatiocyteWorld.hpp"" +#include +#include +#include + +using namespace ecell4; +using namespace ecell4::spatiocyte; + +struct Fixture +{ + const Real3 edge_lengths; + const Real voxel_radius; + const std::shared_ptr rng; + const std::shared_ptr model; + SpatiocyteWorld world; + + Fixture() + : edge_lengths(1e-6, 1e-6, 1e-6), voxel_radius(1e-8), + rng(new GSLRandomNumberGenerator()), model(new NetworkModel()), + world(edge_lengths, voxel_radius, rng) + { + world.bind_to(model); + } +}; + +BOOST_FIXTURE_TEST_SUITE(suite, Fixture) + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_constructor) {} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_t) +{ + BOOST_CHECK_EQUAL(world.t(), 0); + world.set_t(23.4); + BOOST_CHECK_EQUAL(world.t(), 23.4); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_num_species) +{ + BOOST_CHECK_EQUAL(world.list_species().size(), 0); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_has_species) +{ + Species sp(std::string(""Species"")); + BOOST_CHECK(!world.has_species(sp)); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_list_particles) +{ + std::vector> particles( + world.list_particles()); + BOOST_CHECK_EQUAL(particles.size(), 0); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_get_molecule_info) +{ + const Species m(""M"", voxel_radius, 0.0); + const Species a(""A"", voxel_radius, 1.0, ""M""); + model->add_species_attribute(m); + model->add_species_attribute(a); + + const auto info_m = world.get_molecule_info(m); + BOOST_CHECK_EQUAL(info_m.radius, voxel_radius); + BOOST_CHECK_EQUAL(info_m.D, 0.0); + BOOST_CHECK_EQUAL(info_m.loc, """"); + BOOST_CHECK_EQUAL(info_m.dimension, Shape::THREE); + + const auto info_a = world.get_molecule_info(a); + BOOST_CHECK_EQUAL(info_a.radius, voxel_radius); + BOOST_CHECK_EQUAL(info_a.D, 1.0); + BOOST_CHECK_EQUAL(info_a.loc, ""M""); + BOOST_CHECK_EQUAL(info_a.dimension, Shape::THREE); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_update_particles) +{ + SerialIDGenerator sidgen; + ParticleID pid(sidgen()); + Species sp(std::string(""A"")); + const Real3 pos(2e-7, 1e-7, 0); + Real r(0); + Real d(0); + Particle p(sp, pos, r, d); + + model->add_species_attribute(sp); + world.update_particle(pid, p); + + BOOST_CHECK(world.has_species(sp)); + BOOST_CHECK(world.has_particle(pid)); + BOOST_CHECK_EQUAL(world.list_particles().size(), 1); + BOOST_CHECK_EQUAL(world.list_particles(sp).size(), 1); +} + +// BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_register_species) +// { +// Species sp(std::string(""TEST"")); +// +// BOOST_CHECK(world.register_species(sp)); +// BOOST_CHECK(world.has_species(sp)); +// +// std::vector list; +// list.push_back(sp); +// +// BOOST_CHECK(list == world.list_species()); +// } + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_add_molecule) +{ + const Species sp(""TEST"", 1e-8, 1e-12); + model->add_species_attribute(sp); + + const Voxel voxel(world.get_voxel_nearby(edge_lengths / 2.0)); + // BOOST_CHECK(world.place_voxel(sp, coord).second); + BOOST_CHECK(world.new_particle(sp, voxel)); + BOOST_CHECK_EQUAL(world.num_particles(sp), 1); + + std::shared_ptr mt(voxel.get_voxel_pool()); + BOOST_CHECK(!mt->is_vacant()); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_add_molecules) +{ + const Species sp(""TEST"", 1e-8, 1e-12); + model->add_species_attribute(sp); + + const Integer N(60); + BOOST_CHECK(world.add_molecules(sp, N)); + BOOST_CHECK_EQUAL(world.num_particles(sp), N); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_neighbor) +{ + const Voxel voxel(world.get_voxel_nearby(edge_lengths / 2.0)); + const Real3 cp(voxel.position()); + + const Species sp(""TEST"", 1e-8, 1e-12); + model->add_species_attribute(sp); + + for (Integer i(0); i < world.num_neighbors(voxel); ++i) + { + world.new_particle(sp, world.get_neighbor(voxel, i)); + } + std::vector> particles( + world.list_particles()); + for (std::vector>::iterator itr( + particles.begin()); + itr != particles.end(); ++itr) + { + Real3 pos((*itr).second.position()); + BOOST_ASSERT(length(pos - cp) < voxel_radius * 2.1); + } + +#ifdef WITH_HDF5 + world.save(""neighbor.h5""); +#endif +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_add_shape) +{ + const Species sp(""TEST"", 1e-8, 1e-12); + model->add_species_attribute(sp); + + std::shared_ptr sphere( + new Sphere(Real3(5e-7, 5e-7, 5e-7), 5e-7 * 1.5)); + + const Integer n(world.add_structure(sp, sphere)); + BOOST_ASSERT(n > 0); + BOOST_CHECK_EQUAL(world.num_particles(sp), n); + +#ifdef WITH_HDF5 + world.save(""sphere.h5""); +#endif +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_move) +{ + const Species sp(""TEST"", 1e-8, 1e-12); + model->add_species_attribute(sp); + + const Voxel from(world.get_voxel_nearby(Real3(0.3e-6, 0.5e-6, 0.5e-6))); + const Voxel to(world.get_voxel_nearby(Real3(0.5e-6, 0.5e-6, 0.5e-6))); + + BOOST_CHECK(world.new_particle(sp, from)); + BOOST_CHECK(world.move(from, to)); + + std::shared_ptr mt(to.get_voxel_pool()); + BOOST_CHECK(!mt->is_vacant()); + + BOOST_CHECK(world.move(from, to)); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_test_structure) +{ + const Species membrane(""Membrane"", 2.5e-9, 0); + const Species sp(""TEST"", 1e-8, 1e-12, ""Membrane""); + model->add_species_attribute(membrane); + model->add_species_attribute(sp); + + std::shared_ptr sphere( + new Sphere(Real3(2.5e-7, 2.5e-7, 2.5e-7), 2e-7)); + + BOOST_CHECK(world.add_structure(membrane, sphere) == 5892); + BOOST_CHECK(!world.new_particle( + Particle(sp, Real3(2.5e-7, 2.5e-7, 4.5e-7), 2.5e-9, 1e-12))); + BOOST_CHECK(world.new_particle(Particle( + sp, Real3(2.5e-7, 2.5e-7, 4.5e-7 - voxel_radius * 2), 2.5e-9, 1e-12))); + +#ifdef WITH_HDF5 + world.save(""structure.h5""); +#endif +} + +BOOST_AUTO_TEST_CASE(SpatiocyteWorld_offlattice) +{ + const Species membrane(""M"", voxel_radius, 0.0); + const Species speciesA(""A"", voxel_radius, 1e-12, ""M""); + model->add_species_attribute(membrane); + model->add_species_attribute(speciesA); + + std::vector positions; + for (auto i = 0; i < 100; ++i) + { + for (auto j = 0; j < 100; ++j) + { + positions.push_back(Real3(i * 1e-8, j * 1e-8, 0.5e-6)); + } + } + + const OffLattice offlattice(voxel_radius, positions); + world.add_space(offlattice.generate_space(membrane)); + BOOST_CHECK_EQUAL(world.num_particles(membrane), 10000); + + // Check whether molecules can be placed at OffLattice. + BOOST_CHECK(world.add_molecules(speciesA, 100)); + BOOST_CHECK_EQUAL(world.num_particles(speciesA), 100); + BOOST_CHECK_EQUAL(world.num_particles(membrane), 9900); + + // Check whether neighbor voxels can be accessed across spaces. + const auto voxel = world.list_voxels_exact(speciesA).at(0).voxel; + BOOST_CHECK(world.check_neighbor(voxel, """")); +} + +BOOST_AUTO_TEST_SUITE_END() +","C++" +"Multi-scale modeling","ecell/ecell4_base","ecell4/spatiocyte/tests/SpatiocyteSimulator_test.cpp",".cpp","11690","404","#define BOOST_TEST_MODULE ""SpatiocyteSimulator_test"" + +#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST +#include +#else +#define BOOST_TEST_NO_LIB +#include +#endif + +#include + +#include ""../SpatiocyteSimulator.hpp"" +#include +#include + +using namespace ecell4; +using namespace ecell4::spatiocyte; + +const Real DEFAULT_VOXEL_RADIUS = 1e-8; + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_constructor) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(DEFAULT_VOXEL_RADIUS); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp1(""A"", radius, D), sp2(""B"", radius, D), + sp3(""C"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp1); + (*model).add_species_attribute(sp2); + (*model).add_species_attribute(sp3); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_hdf5_save) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(DEFAULT_VOXEL_RADIUS); + const Integer N(60); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp(""A"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + world->add_molecules(sp, N); + BOOST_ASSERT(world->num_molecules(sp) == N); + + SpatiocyteSimulator sim(world, model); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_step_with_single_particle) +{ + const Real L(2.5e-8); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp(""A"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + BOOST_CHECK(world->new_particle( + sp, world->get_voxel_nearby(Real3(1.0e-8, 1.0e-8, 1.0e-8)))); + + SpatiocyteSimulator sim(world, model); + + const std::string hdf5path(""/""); + + for (int i(0); i < 50; ++i) + { + sim.step(); + } +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_step_with_single_species) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Integer N(60); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp(""A"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + world->add_molecules(sp, N / 2); + + BOOST_ASSERT(world->num_molecules(sp) == N / 2); + + SpatiocyteSimulator sim(world, model); + + world->add_molecules(sp, N / 2); + BOOST_ASSERT(world->num_molecules(sp) == N); + + sim.initialize(); + sim.step(); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_save_step_with_single_species) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Integer N(60); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp(""A"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + world->add_molecules(sp, N); + sim.initialize(); + + const std::string hdf5path(""/""); + + for (int i(0); i < 50; ++i) + { + sim.step(); + } +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_save_step_with_periodic) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Integer N(60); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp(""A"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + world->add_molecules(sp, N); + sim.initialize(); + + const std::string hdf5path(""/""); + + for (int i(0); i < 50; ++i) + { + sim.step(); + } +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_unimolecular_reaction) +{ + const Real L(2.5e-8); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Real radius(1.25e-9); + const ecell4::Species sp1(""A"", radius, 1.0e-12), sp2(""B"", radius, 1.1e-12), + sp3(""C"", 2.5e-9, 1.2e-12); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + + model->add_reaction_rule(create_unimolecular_reaction_rule(sp1, sp3, 1e6)); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + BOOST_CHECK(world->add_molecules(sp1, 25)); + BOOST_CHECK(world->add_molecules(sp2, 25)); + sim.initialize(); + + for (Integer i(0); i < 10; ++i) + { + sim.step(); + } + BOOST_ASSERT(world->num_molecules(sp3) > 0); + BOOST_ASSERT(25 - world->num_molecules(sp1) == world->num_molecules(sp3)); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_binding_reaction) +{ + const Real L(2.5e-8); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Real radius(1.25e-9); + const ecell4::Species sp1(""A"", radius, 1.0e-12), sp2(""B"", radius, 1.1e-12), + sp3(""C"", 2.5e-9, 1.2e-12); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + + model->add_reaction_rule( + create_binding_reaction_rule(sp1, sp2, sp3, 1e-20)); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + BOOST_CHECK(world->add_molecules(sp1, 25)); + BOOST_CHECK(world->add_molecules(sp2, 25)); + sim.initialize(); + + for (Integer i(0); i < 20; ++i) + { + sim.step(); + } + Integer num_sp3(world->num_molecules(sp3)); + BOOST_ASSERT(num_sp3 > 0); + BOOST_CHECK_EQUAL(25 - world->num_molecules(sp1), num_sp3); + BOOST_CHECK_EQUAL(25 - world->num_molecules(sp2), num_sp3); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_unbinding_reaction) +{ + const Real L(2.5e-8); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Real radius(1.25e-9); + const ecell4::Species sp1(""A"", radius, 1.0e-12), sp2(""B"", radius, 1.1e-12), + sp3(""C"", 2.5e-9, 1.2e-12); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + model->add_species_attribute(sp2); + model->add_species_attribute(sp3); + + model->add_reaction_rule( + create_unbinding_reaction_rule(sp1, sp2, sp3, 1e5)); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + BOOST_CHECK(world->add_molecules(sp1, 25)); + sim.initialize(); + + for (Integer i(0); i < 10; ++i) + { + sim.step(); + } + const Integer num_sp1(world->num_molecules(sp1)); + BOOST_ASSERT(num_sp1 < 25); + BOOST_CHECK_EQUAL(25 - num_sp1, world->num_molecules(sp2)); + BOOST_CHECK_EQUAL(25 - num_sp1, world->num_molecules(sp3)); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_degradation_reaction) +{ + const Real L(2.5e-8); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Real radius(1.25e-9); + const ecell4::Species sp1(""A"", radius, 1.0e-12); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(sp1); + + model->add_reaction_rule(create_degradation_reaction_rule(sp1, 1e5)); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + BOOST_CHECK(world->add_molecules(sp1, 25)); + sim.initialize(); + + for (Integer i(0); i < 10; ++i) + { + sim.step(); + } + BOOST_ASSERT(world->num_molecules(sp1) < 25); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_finalize) +{ + const Real L(1e-6); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(2.5e-9); + const Integer N(60); + + const Real D(1e-12), radius(2.5e-9); + + ecell4::Species sp(""A"", radius, D); + std::shared_ptr model(new NetworkModel()); + (*model).add_species_attribute(sp); + + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + world->add_molecules(sp, N); + sim.initialize(); + + while (sim.step(0.311111111)) + ; + + sim.finalize(); +} + +BOOST_AUTO_TEST_CASE(SpatiocyteSimulator_test_shape) +{ + const Real L(2.5e-8); + const Real3 edge_lengths(L, L, L); + const Real voxel_radius(1e-9); + Species membrane(""Membrane"", 2.5e-9, 0); + + Species sp(""SpeciesA"", 2.5e-9, 1e-12); + sp.set_attribute(""location"", ""Membrane""); + + std::shared_ptr model(new NetworkModel()); + model->add_species_attribute(membrane); + model->add_species_attribute(sp); + std::shared_ptr rng( + new GSLRandomNumberGenerator()); + std::shared_ptr world( + new SpatiocyteWorld(edge_lengths, voxel_radius, rng)); + + SpatiocyteSimulator sim(world, model); + + std::shared_ptr sphere( + new Sphere(Real3(L / 2, L / 2, L / 2), L * 1 / 3)); + + BOOST_CHECK(world->add_structure(membrane, sphere) > 0); + BOOST_CHECK( + !world->new_particle(Particle(sp, Real3(L / 2, L / 2, L * 5 / 6), + 2.5e-9, 1e-12))); // This should fail + BOOST_CHECK(world->new_particle(Particle( + sp, Real3(L / 2, L / 2, L * 5 / 6 - voxel_radius), 2.5e-9, 1e-12))); + + sim.initialize(); + + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); + sim.step(); +} +","C++" +"Multi-scale modeling","ecell/ecell4_base","conda.recipe/build.sh",".sh","96","5","#!/bin/bash +unset MACOSX_DEPLOYMENT_TARGET +${PYTHON} setup.py install; +${PYTHON} setup.py test; +","Shell" +"Multi-scale modeling","ecell/ecell4_base","misc/benchmark.py",".py","8603","226","import time + +from ecell4 import * + +radius = 0.005 +D = 1 + +def singlerun(f, L, num, max_steps, min_duration=0.0): + """""" + Parameters + ---------- + f : Factory + L : Real + A size of the World + num : Real + The number of molecules + max_steps : Integer + The maximum number of steps + min_duration : Real, optional + The minimum duration + """""" + m = NetworkModel() + m.add_species_attribute(Species(""A"", str(radius), str(D))) + w = f.create_world(ones() * L) + w.bind_to(m) + w.add_molecules(Species(""A""), num) + sim = f.create_simulator(w) + sim.initialize() + tstart = time.time() + i, telapsed = 0, 0.0 + while i < max_steps or telapsed < min_duration: + sim.step() + telapsed = time.time() - tstart + i += 1 + return telapsed / sim.t() + +def run(num_trials, *args): + retval = [] + for _ in range(num_trials): + retval.append(singlerun(*args)) + return retval + +def matrix_sizes(L, N, r): + N = int(min(L / (2 * r), max(3, cbrt(N)))) + return Integer3(N, N, N) + +def partitioned_factory_maker(ftype, *args, **kwargs): + def create_factory(L, num): + return ftype(matrix_sizes(L, num, radius), *args, **kwargs).rng(GSLRandomNumberGenerator(0)) + return create_factory + +def non_partitioned_factory_maker(ftype, *args, **kwargs): + def create_factory(L, num): + return ftype(*args, **kwargs).rng(GSLRandomNumberGenerator(0)) + return create_factory + +def savedata(filename, x, data): + with open(filename, ""a"") as fout: + line = ""{}\t{}"".format(x, ""\t"".join([str(t) for t in data])) + fout.write(line) + fout.write(""\n"") + print(""{} => {}"".format(filename, line)) + +def plotdata(ax, filename, label=None, c=""k"", marker=""s"", lines=None): + lines = lines or [(0, 1.0)] + + import numpy + data = numpy.loadtxt(filename) + # data = numpy.log10(data) + data = numpy.array([(row[0], numpy.mean(row[1: ]), numpy.std(row[1: ])) for row in data]).T + ax.errorbar(data[0], data[1], data[2], fmt='o', color=c, marker=marker, mec=c, label=label) + # ax.plot(data[0], data[0] + data[1][0] - data[0][0], '--', color=c) + + if lines is not None: + left, right = ax.get_xlim() + x = numpy.linspace(left, right, 3) + # x = numpy.logspace(0.5, 6.5, 5) + # x = data[0] + for line in lines: + ax.plot(x, numpy.power(x, line[1]) * (data[1][line[0]] / numpy.power(data[0][line[0]], line[1])), '--', color=c) + + +if __name__ == ""__main__"": + import numpy + import os + import os.path + + def profile1(filename, ns, create_factory, fixed_volume, one_particle_per_step, max_steps, min_duration): + if os.path.isfile(filename): + os.remove(filename) + + numarray = numpy.logspace(*ns).astype(int) + for num in numarray: + if fixed_volume: + L = cbrt(40.0) # 3.42 + else: + L = cbrt(num / 60.0 * 1.0) # 100nM + + if one_particle_per_step: + max_steps_ = num * max_steps + else: + max_steps_ = max_steps + + savedata(filename, num, run(5, create_factory(L, num), L, num, max_steps_, min_duration)) + + def profile2(filename, cs, create_factory, num, one_particle_per_step, max_steps, min_duration): + if os.path.isfile(filename): + os.remove(filename) + + concarray = numpy.logspace(*cs) + for conc in concarray: + volume = num / (conc * 1e-6 * N_A) * 1e-3 + L = cbrt(volume) * 1e+6 + + if one_particle_per_step: + max_steps_ = num * max_steps + else: + max_steps_ = max_steps + + savedata(filename, conc, run(5, create_factory(L, num), L, num, max_steps_, min_duration)) + + def profileall(solvers, ftypes=None): + if ftypes is None: + ftypes = solvers.keys() + + if not os.path.isdir(""N""): + os.mkdir(""N"") + + for ftype in ftypes: + for fixed_volume in (True, False): + if (ftype, fixed_volume) in ((""Spatiocyte"", False), ): + ns = (1.0, 5.0, 9) + else: + ns = (1.0, 6.0, 11) + create_factory, one_particle_per_step, c, marker = solvers[ftype] + filename = ""N/{}-{}.tsv"".format(ftype, ""volume"" if fixed_volume else ""conc"") + profile1(filename, ns, create_factory, fixed_volume, one_particle_per_step, max_steps, min_duration) + + if not os.path.isdir(""C""): + os.mkdir(""C"") + + for ftype in (""eGFRD"", ""BD""): + for num in (300, 3000): + cs = (-3, 3, 7) + create_factory, one_particle_per_step, c, marker = solvers[ftype] + filename = ""C/{}-{:d}.tsv"".format(ftype, num) + profile2(filename, cs, create_factory, num, one_particle_per_step, max_steps, min_duration) + + def plotall(outputfilename, solvers, ftypes=None): + if ftypes is None: + ftypes = sorted(tuple(solvers.keys())) + + import matplotlib + matplotlib.use('Agg') + + import matplotlib.pyplot as plt + plt.rcParams[""font.size""] = 16 + + fig, ax = plt.subplots(1, 1, figsize=(11, 7)) + plt.subplots_adjust(left = 0.10, right = 0.72) + ax.set_xscale(""log"") + ax.set_yscale(""log"") + ax.set_xlim(10.0 ** 0.5, 10.0 ** 6.5) + ax.set_xlabel(""N [# particles]"") + ax.set_ylabel(""time [sec]"") + ax.grid() + + for ftype in ftypes: + for fixed_volume in (True, False): + create_factory, one_particle_per_step, c, marker = solvers[ftype] + filename = ""N/{}-{}.tsv"".format(ftype.replace(""."", ""-""), ""volume"" if fixed_volume else ""conc"") + label = ""{} ({})"".format(ftype, ""volume"" if fixed_volume else ""conc"") + if (ftype, fixed_volume) == (""eGFRD"", True): + plotdata(ax, filename, label, c, ""^"" if fixed_volume else ""v"", [(0, 5.0 / 3.0)]) + elif ftype == ""Spatiocyte"": + plotdata(ax, filename, label, c, ""^"" if fixed_volume else ""v"", [(5, 1.0)]) + else: + if fixed_volume: + plotdata(ax, filename, label, c, ""^"", None) + # plotdata(ax, filename, label, c, ""^"") + else: + plotdata(ax, filename, label, c, ""v"") + + handles, labels = ax.get_legend_handles_labels() + handles = [h[0] for h in handles] # remove the errorbars + ax.legend(handles, labels, loc='upper left', numpoints=1, shadow=True, fontsize=11, bbox_to_anchor=(1.0, 1.0)) + + inset = fig.add_axes([0.16, 0.60, 0.22, 0.26]) + inset.set_xscale(""log"") + inset.set_yscale(""log"") + inset.tick_params(labelsize=11) + inset.set_xlabel(""Concentration [uM]"", fontsize=11) + inset.set_ylabel(""time [sec]"", fontsize=11) + inset.set_xlim(10.0 ** -3.5, 10.0 ** +3.5) + inset.set_ylim(10.0 ** -1.0, 10.0 ** +8.0) + for ftype in (""eGFRD"", ""BD""): + for num in (300, 3000): + create_factory, one_particle_per_step, c, marker = solvers[ftype] + filename = ""C/{}-{:d}.tsv"".format(ftype, num) + if ftype == ""eGFRD"": + if num == 300: + plotdata(inset, filename, c='k', marker=marker, lines=[(0, 2.0 / 3.0), (-1, 1.5)]) + else: + plotdata(inset, filename, c='k', marker=marker, lines=None) + else: + plotdata(inset, filename, c='k', marker=marker, lines=None) + + plt.savefig(outputfilename) + # plt.show() + + max_steps = 10 + min_duration = 10.0 # 1.0 + + solvers = { + ""Mesoscopic"": (non_partitioned_factory_maker(meso.MesoscopicFactory, subvolume_length=0.1), True, ""b"", ""o""), + ""Mesoscopic relaxed"": (non_partitioned_factory_maker(meso.MesoscopicFactory, subvolume_length=0.3), True, ""navy"", ""o""), + ""BD"": (partitioned_factory_maker(bd.BDFactory, bd_dt_factor=1e-5), False, ""k"", ""x""), + ""BD relaxed"": (partitioned_factory_maker(bd.BDFactory, bd_dt_factor=1e-3), False, ""gray"", ""x""), + ""BD eGFRD"": (partitioned_factory_maker(egfrd.BDFactory, bd_dt_factor=1e-5), False, ""silver"", ""v""), + ""eGFRD"": (partitioned_factory_maker(egfrd.EGFRDFactory), True, ""r"", ""d""), + ""Spatiocyte"": (non_partitioned_factory_maker(spatiocyte.SpatiocyteFactory, voxel_radius=radius), False, ""g"", ""o""), + } + + profileall(solvers) + plotall(""benchmark.png"", solvers) +","Python" +"Multi-scale modeling","ecell/ecell4_base","misc/ecell4paraview.py",".py","3652","114","""""""A macro for ParaView + +This is a macro for visualizing the E-Cell4 output with ParaView (http://www.paraview.org/). + +1. Save particles by using `FixedIntervalCSVObserver`. +2. Launch ParaView ($PATH_TO_PARAVIEW/bin/paraview). +3. Add this macro just at the first time (Macros -> Add new macro...). +4. Open the output CSV files (File -> Open, or just Ctr+O). +5. Run the macro (Macros -> ecell4paraview) + +"""""" + +from paraview.simple import * + +meso = GetActiveSource() + +renderView1 = FindViewOrCreate('RenderView1', viewtype='RenderView') +viewLayout1 = GetLayout() + +# create a new 'Programmable Filter' +programmableFilter1 = ProgrammableFilter(Input=meso) +programmableFilter1.Script = """""" +sidmap = None # {3: 3, 4: 4} # A serial ID mapper +r0 = 0.05 # Default radius when the input is zero + +import numpy as np + +inputs0 = inputs[0] + +if sidmap is not None: + sid = inputs0.RowData['sid'].copy() + mask = np.logical_or.reduce([sid == key for key in sidmap.keys()]) + for key, value in sidmap.items(): + sid[sid == key] = value + output.RowData.append(sid[mask], 'sid') +else: + mask = np.ones_like(inputs0.RowData['sid'], dtype=bool) + output.RowData.append(inputs0.RowData['sid'][mask], 'sid') + +for key in ('x', 'y', 'z'): + output.RowData.append(inputs0.RowData[key][mask], key) + +if r0 is not None: + r = inputs0.RowData['r'][mask].copy() + r = np.where(r <= 0, r0, r) + output.RowData.append(r, 'r') +else: + output.RowData.append(inputs0.RowData['r'][mask], 'r') +"""""" +programmableFilter1.RequestInformationScript = '' +programmableFilter1.RequestUpdateExtentScript = '' +programmableFilter1.PythonPath = '' + +# create a new 'Table To Points' +tableToPoints1 = TableToPoints(Input=programmableFilter1) +tableToPoints1.XColumn = 'x' +tableToPoints1.YColumn = 'y' +tableToPoints1.ZColumn = 'z' + +# create a new 'Glyph' +glyph1 = Glyph(Input=tableToPoints1, GlyphType='Sphere') +glyph1.Scalars = ['POINTS', 'r'] +glyph1.ScaleMode = 'scalar' +glyph1.Vectors = ['POINTS', 'None'] +glyph1.ScaleFactor = 1.0 +glyph1.GlyphTransform = 'Transform2' +glyph1.GlyphMode = 'All Points' + +# set active view +SetActiveView(renderView1) + +# set active source +SetActiveSource(glyph1) + +# get color transfer function/color map for 'r' +sidLUT = GetColorTransferFunction('sid') + +# show data in view +glyph1Display_1 = Show(glyph1, renderView1) + +# trace defaults for the display properties. +glyph1Display_1.ColorArrayName = ['POINTS', 'sid'] +glyph1Display_1.LookupTable = sidLUT +glyph1Display_1.GlyphType = 'Arrow' +glyph1Display_1.SetScaleArray = ['POINTS', 'sid'] +glyph1Display_1.ScaleTransferFunction = 'PiecewiseFunction' +glyph1Display_1.OpacityArray = ['POINTS', 'sid'] +glyph1Display_1.OpacityTransferFunction = 'PiecewiseFunction' +glyph1Display_1.SetScalarBarVisibility(renderView1, True) + +# reset view to fit data +renderView1.ResetCamera() + +sidPWF = GetOpacityTransferFunction('sid') +sidLUT.NumberOfTableValues = 32 +sidLUT.ColorSpace = 'HSV' +sidLUT.RescaleTransferFunction(0.0, 32.0) +sidPWF.RescaleTransferFunction(0.0, 32.0) + +# Properties modified on renderView1 +renderView1.UseGradientBackground = 1 + +#### saving camera placements for all active views + +# current camera placement for renderView1 +renderView1.CameraPosition = [-5.776684363101421, 8.094366607688107, 5.7143244602859875] +renderView1.CameraFocalPoint = [2.3135256972163916, 0.550464017316699, 0.5488972440361977] +renderView1.CameraViewUp = [0.237542764231946, 0.7092276746338985, -0.6637541266873143] +renderView1.CameraParallelScale = 3.203095814674732 + +#### uncomment the following to render all views +# RenderAllViews() +# alternatively, if you want to write images, you can use SaveScreenshot(...). +","Python" +"Multi-scale modeling","ecell/ecell4_base","misc/tests/spatiocyte/reversible.py",".py","1336","56","# -*- coding: utf_8 -*- + +import numpy as np +from ecell4 import * +from ecell4.extra.ensemble import ensemble_simulations + +def main(): + radius, D = 5.0e-3, 1.0 + N_A = 60 + U = 0.5 + ka_factor = 0.1 + + number_of_samples = 20 + + kD = 4 * np.pi * (radius * 2) * (D * 2) + ka = kD * ka_factor + kd = ka * N_A * U * U / (1 - U) + kon = ka * kD / (ka + kD) + koff = kd * kon / ka + + with species_attributes(): + A | B | C | {'radius': str(radius), 'D': str(D)} + + with reaction_rules(): + A + B == C | (kon, koff) + + m = get_model() + + rng = GSLRandomNumberGenerator() + rng.seed(0) + + y0 = {'A': N_A, 'B': N_A} + duration = 3 + T = np.linspace(0, duration, 21) + + obs = run_simulation(np.linspace(0, duration, 101), y0, + model=ode.ODENetworkModel(m), + return_type='observer', + solver='ode') + + with species_attributes(): + A | B | C | {'radius': str(radius), 'D': str(D)} + + with reaction_rules(): + A + B == C | (ka, kd) + + m = get_model() + + ensemble_simulations(T, y0, model=m, return_type='matplotlib', + opt_args=('o', obs, '-'), + solver=('spatiocyte', radius), + n=number_of_samples) + +if __name__ == '__main__': + main() +","Python" +"Multi-scale modeling","ecell/ecell4_base","misc/tests/spatiocyte/birth_death.py",".py","870","37","# -*- coding: utf_8 -*- + +import numpy as np +from ecell4 import * +from ecell4.extra.ensemble import ensemble_simulations + +radius, D = 5.0e-3, 1.0 + +with species_attributes(): + A | {'radius': str(radius), 'D': str(D)} + +with reaction_rules(): + ~A > A | 45.0 + A > ~A | 1.5 + +model = get_model() + +rng = GSLRandomNumberGenerator() +rng.seed(0) + +number_of_samples = 20 +y0 = {} +duration = 3 +T = np.linspace(0, duration, 21) +V = 8 + +obs = run_simulation(np.linspace(0, duration, 101), y0, volume=V, + model=ode.ODENetworkModel(model), + return_type='observer', + solver='ode') + +ensemble_simulations(T, y0, volume=V, model=model, + return_type='matplotlib', + opt_args=('o', obs, '-'), + solver=('spatiocyte', radius), + n=number_of_samples) +","Python" +"Multi-scale modeling","ecell/ecell4_base","misc/tests/spatiocyte/reversible_diffusion_limited.py",".py","1338","56","# -*- coding: utf_8 -*- + +import numpy as np +from ecell4 import * +from ecell4.extra.ensemble import ensemble_simulations + +def main(): + radius, D = 5.0e-3, 1.0 + N_A = 60 + U = 0.5 + ka_factor = 10 + + number_of_samples = 20 + + kD = 4 * np.pi * (radius * 2) * (D * 2) + ka = kD * ka_factor + kd = ka * N_A * U * U / (1 - U) + kon = ka * kD / (ka + kD) + koff = kd * kon / ka + + with species_attributes(): + A | B | C | {'radius': str(radius), 'D': str(D)} + + with reaction_rules(): + A + B == C | (kon, koff) + + m = get_model() + + rng = GSLRandomNumberGenerator() + rng.seed(0) + + y0 = {'A': N_A, 'B': N_A} + duration = 0.35 + T = np.linspace(0, duration, 21) + + obs = run_simulation(np.linspace(0, duration, 101), y0, + model=ode.ODENetworkModel(m), + return_type='observer', + solver='ode') + + with species_attributes(): + A | B | C | {'radius': str(radius), 'D': str(D)} + + with reaction_rules(): + A + B == C | (ka, kd) + + m = get_model() + + ensemble_simulations(T, y0, model=m, return_type='matplotlib', + opt_args=('o', obs, '-'), + solver=('spatiocyte', radius), + n=number_of_samples) + +if __name__ == '__main__': + main() +","Python" +"Multi-scale modeling","ecell/ecell4_base","misc/tests/spatiocyte/msd.py",".py","1608","59","# -*- coding: utf_8 -*- + +import os +import numpy as np +import matplotlib.pyplot as plt +from ecell4 import * + +def main(): + radius, D = 5.0e-3, 1.0 + model = NetworkModel() + model.add_species_attribute(Species(""A"", str(radius), str(D))) + + rng = GSLRandomNumberGenerator() + rng.seed(0) + + factory = spatiocyte.SpatiocyteFactory(radius).rng(rng) + def calc_squared_displacements(trajectory): + origin = trajectory[0] + return list(map(lambda pos: length_sq(pos - origin), trajectory)) + + def run_and_calc_msd(duration): + world = factory.create_world(Real3(1.0, 1.0, 1.0)) + world.bind_to(model) + world.add_molecules(Species(""A""), 60) + + obs = FixedIntervalTrajectoryObserver(0.01) + simulator = factory.create_simulator(world) + simulator.run(duration, obs) + + times = np.array(obs.t()) + msds = np.mean(list(map(calc_squared_displacements, obs.data())), axis=0) + + return times, msds + + def test_msd(num, duration): + times, msds = run_and_calc_msd(duration) + for _ in range(0, num - 1): + msds += run_and_calc_msd(duration)[1] + msds /= num + return times, msds + + times, msds = test_msd(10, 1.00) + + + # Plot + + plt.plot(times, 6*D*times, 'k-', label='Expected') + plt.plot(times[::10], msds[::10], 'ro', label='Spatiocyte') + plt.xlabel('Time') + plt.ylabel('Mean Squared Displacement') + plt.legend(loc='best') + plt.title('MSD in a space') + + name=os.path.splitext(os.path.basename(__file__))[0] + plt.savefig(name+'.png') + +if __name__ == '__main__': + main() +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/__init__.py",".py","0","0","","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/rr_descriptor_pyfunc.py",".py","522","15","import unittest +from ecell4_base.core import * + +class ReactionRuleDescriptorPyfuncTest(unittest.TestCase): + + def test_clone(self): + m = NetworkModel() + rr = create_binding_reaction_rule(Species(""A""), Species(""B""), Species(""C""), 0.0) + desc = ReactionRuleDescriptorPyfunc(lambda r, p, v, t, rc, pc: 0.1 * r[0] * r[1], ""test"") + rr.set_descriptor(desc) + m.add_reaction_rule(rr) + + self.assertTrue(rr.has_descriptor()) + self.assertTrue(m.reaction_rules()[0].has_descriptor()) +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/species.py",".py","5611","150","import unittest +import copy +from ecell4_base.core import * + +class UnitSpeciesTest(unittest.TestCase): + def test_constructor(self): + usp = UnitSpecies() + usp = UnitSpecies(""A"") + + def test_getter(self): + usp = UnitSpecies(""A"") + self.assertEqual(usp.name(), ""A"") + self.assertEqual(usp.serial(), ""A"") + + +class SpeciesTest(unittest.TestCase): + def test_serial(self): + sp = Species('A') + self.assertEqual(sp.serial(), 'A') + + def test_units(self): + sp = Species() + sp.add_unit(UnitSpecies('B')) + sp.add_unit(UnitSpecies('C')) + sp.add_unit(UnitSpecies('A')) + self.assertEqual(sp.serial(), 'B.C.A') + self.assertEqual(len(sp.units()), 3) + + sp = Species('A.B.C') + self.assertEqual(sp.serial(), 'A.B.C') + self.assertEqual(len(sp.units()), 3) + + sp.add_unit(UnitSpecies('D')) + self.assertEqual(sp.serial(), 'A.B.C.D') + self.assertEqual(len(sp.units()), 4) + + units = sp.units() + self.assertEqual(len(units), 4) + + sp = Species('X(a,b=c^1).Y(d=e^1,f=g)') + units = sp.units() + + self.assertEqual(len(sp.units()), 2) + self.assertEqual(len(units), 2) + + self.assertEqual(units[0].name(), 'X') + self.assertEqual(units[1].name(), 'Y') + + units[1].add_site('h', 'i', '') + + sp = Species("" A . B . C.D"") + units = sp.units() + self.assertEqual(len(units), 4) + self.assertEqual(units[0].name(), ""A"") + self.assertEqual(units[1].name(), ""B"") + + def test_attributes(self): + sp = Species('A') + + sp.set_attribute('foo', 'bar') + sp.set_attribute('spam', 'ham') + sp.set_attribute('hoge', 'hage') + + self.assertTrue(sp.has_attribute('spam')) + self.assertTrue(sp.has_attribute('foo')) + self.assertTrue(sp.has_attribute('hoge')) + self.assertFalse(sp.has_attribute('eggs')) + + sp.remove_attribute('spam') + self.assertFalse(sp.has_attribute('spam')) + + self.assertEqual(sp.get_attribute('foo'), 'bar') + self.assertEqual(sp.get_attribute('hoge'), 'hage') + + attrs = sp.list_attributes() + self.assertEqual(len(attrs), 2) + for key, value in attrs: + self.assertTrue(key == 'foo' or key == 'hoge') + self.assertTrue( + (key == 'foo' and value == 'bar') + or (key == 'hoge' and value == 'hage')) + + def test_attribute_types(self): + sp = Species('A') + + sp.set_attribute('key', 'value') + self.assertTrue(isinstance(sp.get_attribute('key'), str)) + sp.set_attribute('key', True) + self.assertTrue(isinstance(sp.get_attribute('key'), bool)) + sp.set_attribute('key', Quantity_Integer(2, 'dimensionless')) + self.assertTrue(isinstance(sp.get_attribute('key'), Quantity_Integer)) + sp.set_attribute('key', Quantity_Real(1.5, 'm**2/s')) + self.assertTrue(isinstance(sp.get_attribute('key'), Quantity_Real)) + + sp.set_attribute('key', 2) + self.assertTrue(isinstance(sp.get_attribute('key'), Quantity_Integer)) + sp.set_attribute('key', 2.0) + self.assertTrue(isinstance(sp.get_attribute('key'), Quantity_Real)) + + def test_operators(self): + self.assertTrue(Species('A') == Species('A')) + self.assertFalse(Species('A') == Species('B')) + self.assertTrue(Species('A') != Species('B')) + + self.assertTrue(Species('A') < Species('B')) + self.assertTrue(Species('B') > Species('A')) + self.assertFalse(Species('A') < Species('A')) + + # self.assertTrue(Species('A') <= Species('A')) # Not implemented yet + + def test_count_species_matches(self): + sp = Species(""A"") + self.assertEqual(count_species_matches(sp, Species(""A"")), 1) + self.assertEqual(count_species_matches(sp, Species(""A.A"")), 2) + + sp = Species(""A.B"") + self.assertEqual(count_species_matches(sp, Species(""A.B"")), 1) + self.assertEqual(count_species_matches(sp, Species(""B.A"")), 1) + + sp = Species(""A(p=u^_)"") + self.assertEqual(count_species_matches(sp, Species(""A(p=u^1).B(b^1)"")), 1) + + def test_pickling(self): + sp = Species(""A"") + sp.set_attribute(""key1"", ""value1"") + sp.set_attribute(""key2"", Quantity_Real(2.0, ""units"")) + sp.set_attribute(""key3"", True) + + self.assertTrue(sp.has_attribute(""key1"")) + self.assertEqual(sp.get_attribute(""key1""), ""value1"") + self.assertTrue(sp.has_attribute(""key2"")) + # self.assertEqual(sp.get_attribute(""key2"").magnitude, Quantity_Real(2.0, ""units"").magnitude) + # self.assertEqual(sp.get_attribute(""key2"").units, Quantity_Real(2.0, ""units"").units) + self.assertEqual(sp.get_attribute(""key2""), Quantity_Real(2.0, ""units"")) + self.assertTrue(sp.has_attribute(""key3"")) + self.assertEqual(sp.get_attribute(""key3""), True) + + another = copy.copy(sp) + self.assertTrue(sp is not another) + self.assertEqual(sp, another) + + self.assertTrue(another.has_attribute(""key1"")) + self.assertEqual(another.get_attribute(""key1""), ""value1"") + self.assertTrue(another.has_attribute(""key2"")) + # self.assertEqual(another.get_attribute(""key2"").magnitude, Quantity_Real(2.0, ""units"").magnitude) + # self.assertEqual(another.get_attribute(""key2"").units, Quantity_Real(2.0, ""units"").units) + self.assertEqual(another.get_attribute(""key2""), Quantity_Real(2.0, ""units"")) + self.assertTrue(another.has_attribute(""key3"")) + self.assertEqual(another.get_attribute(""key3""), True) +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/__init__.py",".py","398","12","from ecell4_base.core import * + +def setUpEqualities(self): + self.addTypeEqualityFunc(Quantity_Real, _assertEqualsQuantity(self)) + self.addTypeEqualityFunc(Quantity_Integer, _assertEqualsQuantity(self)) + +def _assertEqualsQuantity(self): + def wrapper(x, y, msg=None): + self.assertEqual(x.magnitude, y.magnitude, msg) + self.assertEqual(x.units, y.units, msg) + return wrapper +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/network_model.py",".py","2615","71","import unittest +from ecell4_base.core import * + +class NetowrkModelTest(unittest.TestCase): + + def setUp(self): + pass + + def test_constructor(self): + model = NetworkModel() + + def test_add_species_attribute1(self): + model = NetworkModel() + sp1, sp2 = Species(""A""), Species(""B"") + + self.assertFalse(model.has_species_attribute(sp1)) + self.assertFalse(model.has_species_attribute(sp2)) + + model.add_species_attribute(sp1) + self.assertTrue(model.has_species_attribute(sp1)) + self.assertFalse(model.has_species_attribute(sp2)) + + model.remove_species_attribute(sp1) + self.assertFalse(model.has_species_attribute(sp1)) + self.assertFalse(model.has_species_attribute(sp2)) + + def test_add_species_attribute2(self): + model = NetworkModel() + sp1, sp2 = Species(""A""), Species(""B"") + sp1.set_attribute('spam', 'ham') + sp2.set_attribute('spam', 'eggs') + self.assertTrue(model.update_species_attribute(sp1)) + self.assertTrue(model.update_species_attribute(sp2)) + + sp = model.apply_species_attributes(Species('A')) + self.assertTrue(sp.has_attribute('spam')) + self.assertEqual(sp.get_attribute('spam'), 'ham') + + sp1 = Species(""A"") + sp1.set_attribute('spam', 'parrot') + self.assertFalse(model.update_species_attribute(sp1)) + + sp = model.apply_species_attributes(Species('A')) + self.assertTrue(sp.has_attribute('spam')) + self.assertEqual(sp.get_attribute('spam'), 'parrot') + + def test_query_reaction_rule(self): + model = NetworkModel() + + sp1, sp2, sp3 = Species(""A""), Species(""B""), Species(""C"") + rr1 = create_degradation_reaction_rule(sp1, 1) + rr2 = create_unimolecular_reaction_rule(sp1, sp2, 1) + rr3 = create_binding_reaction_rule(sp1, sp2, sp3, 1) + rr4 = create_unbinding_reaction_rule(sp3, sp1, sp2, 1) + model.add_reaction_rule(rr1) + model.add_reaction_rule(rr2) + model.add_reaction_rule(rr3) + model.add_reaction_rule(rr4) + rules1 = model.query_reaction_rules(sp1) + rules2 = model.query_reaction_rules(sp2) + rules3 = model.query_reaction_rules(sp3) + rules4 = model.query_reaction_rules(sp1, sp2) + + self.assertEqual(len(rules1), 2) + self.assertEqual(len(rules2), 0) + self.assertEqual(len(rules3), 1) + self.assertEqual(len(rules3[0].products()), 2) + self.assertEqual(len(rules4), 1) + self.assertEqual(len(rules4[0].products()), 1) + self.assertEqual(rules4[0].products()[0].serial(), ""C"") +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/types.py",".py","3434","110","import unittest +from ecell4_base.core import * +import math + +class Real3Test(unittest.TestCase): + def setUp(self): + self.addTypeEqualityFunc(Real3, Real3.__eq__) + + def test_constructor(self): + x = Real3(1, 2, 3) + + def test_tuple_and_list(self): + x = Real3(1, 2, 3) + self.assertEqual(tuple(x), (1.0, 2.0, 3.0)) + self.assertEqual(list(x), [1.0, 2.0, 3.0]) + + def test_operators(self): + x = Real3(7, 4, 9) + y = Real3(1, 2, 3) + self.assertEqual(x + y, Real3(8, 7, 12)) + self.assertEqual(x - y, Real3(6, 2, 6)) + self.assertEqual(x * 2, Real3(14, 8, 18)) + self.assertEqual(2 * x, Real3(14, 8, 18)) + self.assertEqual(x / 3, Real3(3.5, 2, 4.5)) + + def test_abs(self): + x = Real3(1, 2, 3) + self.assertEqual(abs(x), x) + self.assertEqual(abs(Real3(-1, 2, -3)), Real3(1, 2, 3)) + + def test_length(self): + x = Real3(1, 2, 3) + sq = 1*1 + 2*2 + 3*3 + self.assertEqual(length_sq(x), sq) + self.assertEqual(length(x), math.sqrt(sq)) + + def test_product(self): + x = Real3(1, 2, 3) + y = Real3(4, 5, 2) + self.assertEqual(dot_product(x, y), 1*4 + 2*5 + 3*2) + self.assertEqual(dot_product(y, x), 1*4 + 2*5 + 3*2) + self.assertEqual(cross_product(x, y), Real3(-11, 10, -3)) + self.assertEqual(cross_product(x, y), Real3(11, -10, 3)) + +class Integer3Test(unittest.TestCase): + def setUp(self): + self.addTypeEqualityFunc(Integer3, Integer3.__eq__) + + def test_constructor(self): + x = Integer3(1, 2, 3) + + def test_tuple_and_list(self): + x = Integer3(1, 2, 3) + self.assertEqual(tuple(x), (1, 2, 3)) + self.assertEqual(list(x), [1, 2, 3]) + + def test_operators(self): + x = Integer3(6, 0, 2) + y = Integer3(1, 2, 3) + self.assertEqual(x + y, Integer3(7, 2, 5)) + self.assertEqual(x - y, Integer3(5, -2, 1)) + self.assertEqual(x * 2, Integer3(12, 0, 4)) + # self.assertEqual(2 * x, Integer3(12, 0, 4)) + + def test_abs(self): + self.assertEqual(abs(Integer3(1, 2, 3)), Integer3(1, 2, 3)) + self.assertEqual(abs(Integer3(-1, 2, -3)), Integer3(1, 2, 3)) + + def test_length(self): + x = Integer3(1, 2, 3) + sq = 1*1 + 2*2 + 3*3 + self.assertEqual(length_sq(x), sq) + self.assertEqual(length(x), math.sqrt(sq)) + + def test_product(self): + x = Integer3(1, 2, 3) + y = Integer3(4, 5, 2) + self.assertEqual(dot_product(x, y), 1*4 + 2*5 + 3*2) + self.assertEqual(dot_product(y, x), 1*4 + 2*5 + 3*2) + + +class QuantityTest(unittest.TestCase): + def test_quantity_real(self): + q = Quantity_Real(0.0) + self.assertEqual(q.magnitude, 0.0) + self.assertEqual(q.units, """") + + q = Quantity_Real(1.0, ""nm"") + self.assertEqual(q.magnitude, 1.0) + self.assertEqual(q.units, ""nm"") + + q.magnitude = 2.0 + q.units = ""m/s"" + self.assertEqual(q.magnitude, 2.0) + self.assertEqual(q.units, ""m/s"") + + def test_quantity_integer(self): + q = Quantity_Integer(0) + self.assertEqual(q.magnitude, 0) + self.assertEqual(q.units, """") + + q = Quantity_Integer(1, ""a"") + self.assertEqual(q.magnitude, 1) + self.assertEqual(q.units, ""a"") + + q.magnitude = 2 + q.units = ""yen"" + self.assertEqual(q.magnitude, 2) + self.assertEqual(q.units, ""yen"") +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/particle.py",".py","862","28","import unittest +from ecell4_base.core import * + +class ParticleIDTest(unittest.TestCase): + def test_constructor(self): + pid = ParticleID() + pid = ParticleID((1, 2)) + + def test_lot_serial(self): + pid = ParticleID() + self.assertEqual(pid.lot(), 0) + self.assertEqual(pid.serial(), 0) + + pid = ParticleID((1, 2)) + self.assertEqual(pid.lot(), 1) + self.assertEqual(pid.serial(), 2) + +class ParticleTest(unittest.TestCase): + def test_constructor(self): + p = Particle(Species(""A""), Real3(1,2,3), 1.0e-5, 1.0e-12) + + def test_variables(self): + p = Particle(Species(""A""), Real3(1,2,3), 1.0e-5, 1.0e-12) + self.assertEqual(p.species().serial(), ""A"") + self.assertEqual(p.position(), Real3(1,2,3)) + self.assertEqual(p.radius(), 1.0e-5) + self.assertEqual(p.D(), 1.0e-12) +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/core/reaction_rule.py",".py","4688","130","import unittest +import copy +from ecell4_base.core import * +from . import setUpEqualities + +class ReactionRuleDescriptor(unittest.TestCase): + def setUp(self): + setUpEqualities(self) + + def test_mass_action(self): + d = ReactionRuleDescriptorMassAction(1.0) + self.assertEqual(d.k(), 1.0) + self.assertEqual(d.get_k(), Quantity_Real(1.0, '')) + + d.set_k(2.0) + self.assertEqual(d.k(), 2.0) + self.assertEqual(d.get_k(), Quantity_Real(2.0, '')) + + d.set_k(Quantity_Real(3.0, 'm')) + self.assertEqual(d.k(), 3.0) + self.assertEqual(d.get_k(), Quantity_Real(3.0, 'm')) + + self.assertEqual(d.reactant_coefficients(), []) + self.assertEqual(d.product_coefficients(), []) + + def test_pyfunc(self): + d = ReactionRuleDescriptorPyfunc( + lambda reactants, products, volume, t, reactant_coefs, product_coefs: 3.14, + ""pyfunc_descriptor"") + self.assertEqual(d.as_string(), ""pyfunc_descriptor"") + + self.assertEqual(d.propensity([], [], 1.0, 1.0e-5), 3.14) + + self.assertEqual(d.reactant_coefficients(), []) + self.assertEqual(d.product_coefficients(), []) + + +class ReactionRuleTest(unittest.TestCase): + def setUp(self): + setUpEqualities(self) + + def test_constructor(self): + reactant = Species(""A"") + product = Species(""B"") + + rr = ReactionRule() + rr = ReactionRule([reactant], [product]) + rr = ReactionRule([reactant], [product], 1.0) + rr = ReactionRule([reactant], [product], Quantity_Real(1.0)) + rr = ReactionRule([reactant], [product], Quantity_Real(1.0, ""/s"")) + + def test_getters(self): + reactant = Species(""A"") + product = Species(""B"") + quantity = Quantity_Real(1.5, ""/s"") + rr = ReactionRule([reactant], [product], quantity) + + self.assertEqual(rr.k(), 1.5) + self.assertEqual(rr.get_k(), quantity) + self.assertEqual(rr.reactants(), [reactant]) + self.assertEqual(rr.products(), [product]) + self.assertEqual(rr.as_string(), ""A>B|1.5"") + + self.assertEqual(rr.count([]), 0) + self.assertEqual(rr.count([reactant]), 1) + self.assertEqual(rr.count([product]), 0) + self.assertEqual(rr.count([reactant, product]), 0) + + def test_policy(self): + rr = ReactionRule() + self.assertEqual(rr.policy(), ReactionRule.STRICT) + + rr.set_policy(ReactionRule.IMPLICIT) + self.assertEqual(rr.policy(), ReactionRule.IMPLICIT) + + rr.set_policy(ReactionRule.DESTROY) + self.assertEqual(rr.policy(), ReactionRule.DESTROY) + + + def test_descriptor(self): + rr = ReactionRule() + self.assertFalse(rr.has_descriptor()) + self.assertEqual(rr.get_descriptor(), None) + + # rr.set_descriptor() + + def test_pickling(self): + k = Quantity_Real(2.0, 'micrometer ** 2 / second') + policy = ReactionRule.DESTROY + + rr = ReactionRule() + rr.add_reactant(Species('A')) + rr.add_reactant(Species('B')) + rr.add_product(Species('C')) + rr.set_k(k) + rr.set_policy(policy) + rr.set_attribute(""key1"", ""value1"") + rr.set_attribute(""key2"", Quantity_Real(2.0, ""units"")) + rr.set_attribute(""key3"", True) + + self.assertEqual(len(rr.reactants()), 2) + self.assertEqual(len(rr.products()), 1) + self.assertEqual(rr.get_k(), k) + self.assertEqual(rr.k(), k.magnitude) + self.assertFalse(rr.has_descriptor()) + self.assertEqual(rr.policy(), policy) + self.assertTrue(rr.has_attribute(""key1"")) + self.assertEqual(rr.get_attribute(""key1""), ""value1"") + self.assertTrue(rr.has_attribute(""key2"")) + self.assertEqual(rr.get_attribute(""key2""), Quantity_Real(2.0, ""units"")) + self.assertTrue(rr.has_attribute(""key3"")) + self.assertEqual(rr.get_attribute(""key3""), True) + + another = copy.copy(rr) + self.assertTrue(rr is not another) + self.assertEqual(rr, another) + + self.assertEqual(len(another.reactants()), 2) + self.assertEqual(len(another.products()), 1) + self.assertEqual(another.get_k(), k) + self.assertEqual(another.k(), k.magnitude) + self.assertFalse(another.has_descriptor()) + self.assertEqual(another.policy(), policy) + self.assertTrue(another.has_attribute(""key1"")) + self.assertEqual(another.get_attribute(""key1""), ""value1"") + self.assertTrue(another.has_attribute(""key2"")) + self.assertEqual(another.get_attribute(""key2""), Quantity_Real(2.0, ""units"")) + self.assertTrue(another.has_attribute(""key3"")) + self.assertEqual(another.get_attribute(""key3""), True) +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/spatiocyte/__init__.py",".py","68","3","from ecell4_base.core import * +from ecell4_base.spatiocyte import * +","Python" +"Multi-scale modeling","ecell/ecell4_base","tests/spatiocyte/offlattice.py",".py","1208","37","import unittest +from ecell4_base.core import * +from ecell4_base.spatiocyte import * + +class OffLatticeTest(unittest.TestCase): + + def setUp(self): + self.voxel_radius = 0.005 + + coordinates = [Real3(x, 0.0, 0.0) for x in range(0,10)] + connections = [(x, x+1) for x in range(0,9)] + self.offlattice = OffLattice(self.voxel_radius, coordinates, connections) + + def test_constructor(self): + species = Species('Base') + model = NetworkModel() + model.add_species_attribute(species) + + world = SpatiocyteWorld(ones(), self.voxel_radius) + world.bind_to(model) + world.add_offlattice(species, self.offlattice) + + def test_add_molecules(self): + base = Species('Base', radius=self.voxel_radius, D=0.0) + species = Species('A', radius=self.voxel_radius, D=1.0, location='Base') + + model = NetworkModel() + model.add_species_attribute(base) + model.add_species_attribute(species) + + world = SpatiocyteWorld(ones(), self.voxel_radius) + world.bind_to(model) + world.add_offlattice(base, self.offlattice) + + world.add_molecules(species, 5) + self.assertEqual(5, world.num_molecules(species)) +","Python"