text
stringlengths
0
1.05M
meta
dict
from funcserver import Server class CalcAPI(object): def __init__(self, ignore_divbyzero=False): self.ignore_divbyzero = ignore_divbyzero def add(self, a, b): '''Computes the sum of @a and @b''' return a + b def sub(self, a, b): '''Computes the difference of @a and @b''' return a - b def mul(self, a, b): '''Computes the product of @a and @b''' return a * b def div(self, a, b): '''Computes the division of @a by @b''' if self.ignore_divbyzero: return 0 return a / b class CalcServer(Server): NAME = 'CalcServer' DESC = 'Calculation Server' def prepare_api(self): return CalcAPI(self.args.ignore_divbyzero) def define_args(self, parser): super(CalcServer, self).define_args(parser) parser.add_argument('--ignore-divbyzero', default=False, action='store_true', help='Ignore division by zero errors') if __name__ == '__main__': CalcServer().start()
{ "repo_name": "prashanthellina/funcserver", "path": "examples/calc_server.py", "copies": "1", "size": "1025", "license": "mit", "hash": 2591755705099471000, "line_mean": 25.9736842105, "line_max": 64, "alpha_frac": 0.5824390244, "autogenerated": false, "ratio": 3.5839160839160837, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46663551083160837, "avg_score": null, "num_lines": null }
from funcserver import Server class CalcAPI(object): def __init__(self, ignore_divbyzero=False): self.ignore_divbyzero = ignore_divbyzero def add(self, a, b): """Computes the sum of @a and @b""" return a + b def sub(self, a, b): """Computes the difference of @a and @b""" return a - b def mul(self, a, b): """Computes the product of @a and @b""" return a * b def div(self, a, b): """Computes the division of @a by @b""" if self.ignore_divbyzero: return 0 return a / b class CalcServer(Server): NAME = "CalcServer" DESC = "Calculation Server" def prepare_api(self): return CalcAPI(self.args.ignore_divbyzero) def define_args(self, parser): super(CalcServer, self).define_args(parser) parser.add_argument( "--ignore-divbyzero", default=False, action="store_true", help="Ignore division by zero errors", ) if __name__ == "__main__": CalcServer().start()
{ "repo_name": "deep-compute/funcserver", "path": "examples/calc_server.py", "copies": "1", "size": "1075", "license": "mit", "hash": -7748296446620226000, "line_mean": 22.8888888889, "line_max": 51, "alpha_frac": 0.5553488372, "autogenerated": false, "ratio": 3.6815068493150687, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47368556865150685, "avg_score": null, "num_lines": null }
from ..funcs import fmap from ..abc import Monad, Container, Option, Full, Empty from ..utils.compat import wraps from ..utils.decorators import method_optional_kwargs from ..utils.internal import _propagate_self class Either(Monad, Option): """Enhanced version of Maybe. Represents a successful computation or a failed computationi with an error message. Either's unit method returns an instance of Right, which is the minimal needed context for a possible computation. Compare to Haskell's implementation of Either: .. code-block:: Haskell data Either a b = Left a | Right b instance Functor (Either a) where fmap f (Left a) = Left a fmap f (Right b) = Right (f b) instance Applicative (Either a) where pure = Right (Left a) <*> f = Left a (Right b) <*> f = fmap b f instance Monad (Either a) where return = Right (Left e) >>= _ = Left e (Right a) >>= f = f a As said before, Either is like a Maybe that carries an error message when a computation fails. Just like Nothing, (Left a) propagates when it is mapped, applied or bound. And like Just, mapping, applying or binding a (Right b) simply takes the value stored in Right and does the appropriate action. Either is more useful than Maybe when you not only expect to encounter a None (or other failure) but you also want to know why you got that bad result. .. code-block:: Python from random import randint def reporting_none_safe_inc(x): if x is None: print("x was None when incrementing") return None else: return x+1 def reporting_none_safe_sq(x): if x is None: print("x was None when squareing") return None else: return x*x def bad_get_int(): x = randint(1,10) return x if x%2 else None x = bad_get_int() y = reporting_none_safe_inc(reporting_none_safe_sq(x)) Instead, using the Either monad would all you to rewrite this as: .. code-block:: Python def bad_get_int(): x = randint(1,10) if x%2: return Right(x) else: return Left("bad integer returned") def inc(x): return Right(x+1) def sqr(x): return Right(x*x) y = bad_get_int() >> sqr >> inc Unlike Maybe, Either doesn't have a default checker. You must provide a Left with an error or a Right with a value to be returned, as well as the condition which causes that result. Other than that, it acts like Maybe in all respects. If a Left is mapped, applied or bound, the Left simply propagates itself until the end of the chain. But a Right will allow the computations to still run. Either is also combined with the Option class, allowing for a recovering of a potentially failed computation through the get_or, get_or_call,or_else and or_call methods. Recovery is only possible on a Left, as a Right is already a successful computation. Either also provides a decorator: ``Either.as_wrapper`` which will attempt to call the wrapped function. If no errors are raised, then the result is returned wrapped in a Right. If the expected error (by default Exception) is raised, then the exception is wrapped in a Left and returned instead. However, if any other errors are encountered, then the exception is propagate until caught or the program exits. """ __slots__ = () def __bool__(self): return isinstance(self, Right) __nonzero__ = __bool__ @method_optional_kwargs @staticmethod def as_wrapper(func, expect=Exception): """Either based decorator. Tries to call the wrapped function and if successful returns the value wrapped in a Right. If the expected exception occurs, the exception is wrapped in a Left. """ @wraps(func) def tryer(*args, **kwargs): try: return Right(func(*args, **kwargs)) except expect as e: return Left(e) return tryer @staticmethod def unit(v): return Right(v) class Left(Either, Empty): """Similar to Nothing in that it only returns itself when fmap, apply or bind is called. However, Left also carries an error message instead of representing an unknown failed computation """ __slots__ = () def __repr__(self): return "Left {!r}".format(self.v) def __eq__(self, other): return isinstance(other, Left) and self.v == other.v fmap = apply = bind = _propagate_self def _get_val(self): return self._v @staticmethod def or_else(default): return Right(default) if (default is not None) \ else Left("None provided") @staticmethod def or_call(func, *args, **kwargs): return Either.as_wrapper(func)(*args, **kwargs) class Right(Either, Full): """Represents a result of a computation. Similar to Just except it is semantically a finished computation. """ __slots__ = () def __new__(cls, v): return Container.__new__(cls) def __eq__(self, other): return isinstance(other, Right) and other.v == self.v def __repr__(self): return "Right {!r}".format(self.v) def fmap(self, func): return Right(func(self.v)) def apply(self, applicative): return fmap(self.v, applicative) def bind(self, bindee): return bindee(self.v) def filter(self, predicate): msg = "{!s} false with input {!r}".format(predicate.__name__, self.v) return self if predicate(self.v) else Left(msg)
{ "repo_name": "justanr/pynads", "path": "pynads/concrete/either.py", "copies": "1", "size": "5880", "license": "mit", "hash": -1962756779414803000, "line_mean": 31.3076923077, "line_max": 79, "alpha_frac": 0.6154761905, "autogenerated": false, "ratio": 4.16135881104034, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.527683500154034, "avg_score": null, "num_lines": null }
from funcs import * from flask_socketio import send, emit print("defining socks...") # SOCKETIO DEFINITIONS @sio.on('connect', namespace='/') def io_connected(): ip = request.environ['REMOTE_ADDR'] if current_user.is_authenticated: connected[current_user.gccid] = "{} {}".format(current_user.fname, current_user.lname) print("{} {} joined the party from {}!".format(current_user.fname, current_user.lname, ip)) else: print("Somebody tried to join from {}".format(ip)) return False # not allowed here update_online() @sio.on('disconnect', namespace='/') def io_disconnected(): if current_user.is_authenticated: print("{} {} left the party!".format(current_user.fname, current_user.lname)) if current_user.gccid in connected: del connected[current_user.gccid] else: return False #print('somebody left the party') update_online() @sio.on('oldPwdType') def oldPwdType(old): if current_user.is_authenticated: emit('pwdVerify', current_user.check_password(old)) else: return False @sio.on('lockEvent') def lockEvent(eventid): if current_user.is_editor: event = Opps.query.get(int(eventid)) #print(event.name) if event.locked: event.locked = False else: event.locked = True db.session.commit() #print(event.locked) emit('eventLock', {'event':str(event.id), 'locked':event.locked}) else: return False @sio.on('toggleSignUps') def toggleSignUps(): if current_user.is_editor: allusers = Users.query.order_by(Users.lname.asc()) if allcansignup(): for user in allusers: user.cansignup = False else: for user in allusers: user.cansignup = True db.session.commit() emit('signUpsAvailable', {'available': allcansignup()}) else: return False @sio.on('getSignUps') def getSignUps(): if current_user.is_authenticated: emit('signUpsAvailable', {'available': allcansignup()}) else: return False @sio.on('changePhoneNumber') def changePhoneNumber(phone): if current_user.is_authenticated: current_user.phone = int(phone) db.session.commit() emit('phoneNumberChanged', current_user.formatPhone()) else: return False @sio.on('signUp') def signUp( data): if current_user.is_authenticated: #print(data['opt']) usr = current_user #print(usr) ev = Opps.query.get(int(data['ev'])) #print(ev) if bool(data['opt']): if not ev in usr.preferredOpps: usr.preferredOpps.append(ev) if ev in usr.opps: usr.opps.remove(ev) else: usr.preferredOpps.remove(ev) else: if not ev in usr.opps: usr.opps.append(ev) if ev in usr.preferredOpps: usr.preferredOpps.remove(ev) else: usr.opps.remove(ev) db.session.commit() events = db.session.query(Opps).filter(Opps.date > datetime.now()).filter(Opps.locked == False).order_by(asc(Opps.date)).all() emit('sendEvents', constructEvData(events)) else: return False @sio.on('getEvents') def getEvents(): if current_user.is_authenticated: events = db.session.query(Opps).filter(Opps.date > datetime.now()).filter(Opps.locked == False).order_by(asc(Opps.date)).all() emit('sendEvents', constructEvData(events)) else: return False @sio.on('getMyEvents') def getMyEvents(): if current_user.is_authenticated: myEvents = [] for event in db.session.query(Opps).filter(Opps.date > datetime.now()).filter(Opps.locked == True).order_by(asc(Opps.date)).all(): if current_user in event.users + event.usersPreferred: myEvents.append(event) emit('sendMyEvents', constructEvData(myEvents)) else: return False @sio.on('getPastEvents') def getPastEvents(): if current_user.is_authenticated: myEvents = db.session.query(Opps).filter(Opps.date < datetime.now()).order_by(desc(Opps.date)).all() emit('sendPastEvents', constructEvData(myEvents)) else: return False @sio.on('getFBNeeded') def getFBNeeded(): if current_user.is_authenticated: data = [] allMyFeedback = db.session.query(Feedback).filter(Feedback.user == current_user).all() feedbackDoneFor = [] for item in allMyFeedback: feedbackDoneFor.append(item.event) myPastEvents = [] for event in db.session.query(Opps).filter(Opps.enddate < datetime.now()).order_by(desc(Opps.date)).all(): if current_user in event.users + event.usersPreferred: myPastEvents.append(event) feedbackNeeded = list(set(myPastEvents) - set(feedbackDoneFor)) for event in feedbackNeeded: data.append({ "name":event.name, "id":event.id }) emit('sendFBNeeded', data) else: return False
{ "repo_name": "theapricot/oppapp2", "path": "sockdefs.py", "copies": "1", "size": "5272", "license": "mit", "hash": -6609655224581048000, "line_mean": 31.7453416149, "line_max": 138, "alpha_frac": 0.595599393, "autogenerated": false, "ratio": 3.6534996534996536, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4749099046499653, "avg_score": null, "num_lines": null }
from FuncTable import FuncTable from FuncDef import FuncDef import re def read_fd(fname): func_pat = "([A-Za-z][_A-Za-z00-9]+)\((.*)\)\((.*)\)" func_table = None bias = 0 private = True # parse file f = open(fname, "r") for line in f: l = line.strip() if len(l) > 1 and l[0] != '*': # a command if l[0] == '#' and l[1] == '#': cmdline = l[2:] cmda = cmdline.split(" ") cmd = cmda[0] if cmd == "base": base = cmda[1] func_table = FuncTable(base) elif cmd == "bias": bias = int(cmda[1]) elif cmd == "private": private = True elif cmd == "public": private = False elif cmd == "end": break else: print "Invalid command:",cmda return None # a function else: m = re.match(func_pat, l) if m == None: raise IOError("Invalid FD Format") else: name = m.group(1) # create a function definition func_def = FuncDef(name, bias, private) if func_table != None: func_table.add_func(func_def) # check args args = m.group(2) regs = m.group(3) arg = args.replace(',','/').split('/') reg = regs.replace(',','/').split('/') if len(arg) != len(reg): raise IOError("Reg and Arg name mismatch in FD File") else: if arg[0] != '': num_args = len(arg) for i in range(num_args): func_def.add_arg(arg[i],reg[i]) bias += 6 f.close() return func_table def write_fd(fname, fd, add_private): fo = open(fname, "w") fo.write("##base %s\n" % (fd.get_base_name())) last_bias = 0 last_mode = None funcs = fd.get_funcs() for f in funcs: if not f.is_private() or add_private: # check new mode if f.is_private(): new_mode = "private" else: new_mode = "public" if last_mode != new_mode: fo.write("##%s\n" % new_mode) last_mode = new_mode # check new bias new_bias = f.get_bias() if last_bias + 6 != new_bias: fo.write("##bias %d\n" % new_bias) last_bias = new_bias # build func line = f.get_name() args = f.get_args() if args == None: line += "()()" else: line += "(" + ",".join(map(lambda x : x[0], args)) + ")" line += "(" + "/".join(map(lambda x : x[1], args)) + ")" fo.write("%s\n" % line) fo.write("##end\n") fo.close()
{ "repo_name": "alpine9000/amiga_examples", "path": "tools/external/amitools/amitools/fd/FDFormat.py", "copies": "1", "size": "2676", "license": "bsd-2-clause", "hash": -3015278093927857000, "line_mean": 27.4787234043, "line_max": 67, "alpha_frac": 0.456651719, "autogenerated": false, "ratio": 3.444015444015444, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44006671630154437, "avg_score": null, "num_lines": null }
from functional.core import ExampleImage def check_valid(source_image, reference_image): data = source_image.create_image() assert reference_image.valid_image(data) def check_invalid(source_image, reference_image): data = source_image.create_image() assert not reference_image.valid_image(data) def test_image_check_valid_color(): check_valid( ExampleImage(123, True), ExampleImage(123, True)) def test_image_check_valid_color_borders(): check_valid( ExampleImage(123, True) .add_border(10, 0, 20, 30, (100, 100, 0)) .add_border(20, 10, 0, 30, (0, 200, 100)), ExampleImage(123, True) .add_border(10, 0, 20, 30, (100, 100, 0)) .add_border(20, 10, 0, 30, (0, 200, 100))) def test_image_check_valid_color_borders_crop(): check_valid( ExampleImage(123, True) .add_border(10, 0, 20, 30, (100, 100, 0)), ExampleImage(123, True) .add_border(10, 0, 20, 30, (100, 100, 0)) .add_border(20, 10, 0, 30, (0, 200, 100)) .border_count_to_check(1)) def test_image_check_valid_bw(): check_valid( ExampleImage(123, False), ExampleImage(123, False)) def test_image_check_valid_bw_borders(): check_valid( ExampleImage(123, False) .add_border(10, 0, 20, 30, 100) .add_border(20, 10, 0, 30, 50), ExampleImage(123, False) .add_border(10, 0, 20, 30, 100) .add_border(20, 10, 0, 30, 50)) def test_image_check_valid_bw_borders_crop(): check_valid( ExampleImage(123, False) .add_border(10, 0, 20, 30, 100), ExampleImage(123, False) .add_border(10, 0, 20, 30, 100) .add_border(20, 10, 0, 30, 50) .border_count_to_check(1)) def test_image_check_invalid_color(): check_invalid( ExampleImage(1023, True), ExampleImage(1022, True)) check_invalid( ExampleImage(1023, True), ExampleImage(511, True)) def test_image_check_invalid_color_borders(): check_invalid( ExampleImage(123, True) .add_border(10, 20, 30, 40, (100, 200, 100)), ExampleImage(123, True) .add_border(10, 0, 0, 40, (100, 200, 100))) def test_image_check_invalid_color_borders_crop(): check_invalid( ExampleImage(123, True) .add_border(10, 0, 20, 30, (100, 100, 0)), ExampleImage(123, True) .add_border(10, 0, 20, 30, (100, 100, 0)) .border_count_to_check(0)) def test_image_check_invalid_bw(): check_invalid( ExampleImage(1023, False), ExampleImage(1022, False)) check_invalid( ExampleImage(1023, False), ExampleImage(511, False)) def test_image_check_invalid_bw_borders(): check_invalid( ExampleImage(123, False) .add_border(10, 20, 30, 40, 100), ExampleImage(123, False) .add_border(10, 0, 0, 40, 100)) def test_image_check_invalid_bw_borders_crop(): check_invalid( ExampleImage(123, False) .add_border(10, 0, 20, 30, 100), ExampleImage(123, False) .add_border(10, 0, 20, 30, 100) .border_count_to_check(0)) def test_image_check_invalid_mixed(): check_invalid( ExampleImage(123, True), ExampleImage(123, False)) check_invalid( ExampleImage(123, False), ExampleImage(123, True)) def test_image_check_valid_rotation(): check_valid( ExampleImage(1, True), ExampleImage(512, True) .set_validation_rotation(180)) def test_image_check_invalid_rotation(): check_invalid( ExampleImage(1, True), ExampleImage(1, True) .set_validation_rotation(180)) def test_image_check_valid_file(tmpdir): image1 = ExampleImage(123, True) image2 = ExampleImage(123, True) filename = str(tmpdir.join("image.jpg")) image1.save(filename) assert image2.valid(filename) def test_image_check_invalid_file(tmpdir): image1 = ExampleImage(123, True) image2 = ExampleImage(321, True) filename = str(tmpdir.join("image.jpg")) image1.save(filename) assert not image2.valid(filename)
{ "repo_name": "atrosinenko/lecture-notes-compiler", "path": "tests/functional/core_image_test.py", "copies": "1", "size": "4270", "license": "mit", "hash": 6374412110839996000, "line_mean": 26.7272727273, "line_max": 57, "alpha_frac": 0.5901639344, "autogenerated": false, "ratio": 3.2795698924731185, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4369733826873119, "avg_score": null, "num_lines": null }
from functional.execution import ExecutionEngine from functional.transformations import CACHE_T class Lineage(object): """ Class for tracking the lineage of transformations, and applying them to a given sequence. """ def __init__(self, prior_lineage=None, engine=None): """ Construct an empty lineage if prior_lineage is None or if its not use it as the list of current transformations :param prior_lineage: Lineage object to inherit :return: new Lineage object """ self.transformations = ( [] if prior_lineage is None else list(prior_lineage.transformations) ) self.engine = ( (engine or ExecutionEngine()) if prior_lineage is None else prior_lineage.engine ) def __repr__(self): """ Returns readable representation of Lineage :return: readable Lineage """ return "Lineage: " + " -> ".join( ["sequence"] + [transform.name for transform in self.transformations] ) def __len__(self): """ Number of transformations in lineage :return: number of transformations """ return len(self.transformations) def __getitem__(self, item): """ Return specific transformation in lineage. :param item: Transformation to retrieve :return: Requested transformation """ return self.transformations[item] def apply(self, transform): """ Add the transformation to the lineage :param transform: Transformation to apply """ self.transformations.append(transform) def evaluate(self, sequence): """ Compute the lineage on the sequence. :param sequence: Sequence to compute :return: Evaluated sequence """ last_cache_index = self.cache_scan() transformations = self.transformations[last_cache_index:] return self.engine.evaluate(sequence, transformations) def cache_scan(self): """ Scan the lineage for the index of the most recent cache. :return: Index of most recent cache """ try: return len(self.transformations) - self.transformations[::-1].index(CACHE_T) except ValueError: return 0
{ "repo_name": "EntilZha/PyFunctional", "path": "functional/lineage.py", "copies": "2", "size": "2367", "license": "mit", "hash": -1214264504779127600, "line_mean": 28.9620253165, "line_max": 95, "alpha_frac": 0.6020278834, "autogenerated": false, "ratio": 4.762575452716298, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6364603336116299, "avg_score": null, "num_lines": null }
from functional import seq from .deck import Deck from .note import Note from ..anki.adapters.anki_deck import AnkiDeck from ..anki.adapters.note_model_file_provider import NoteModelFileProvider def from_collection(collection, name, deck_metadata=None, is_child=False) -> Deck: anki_dict = collection.decks.byName(name) if AnkiDeck(anki_dict).is_dynamic: return None deck = Deck(NoteModelFileProvider, anki_dict, is_child) deck.collection = collection deck._update_fields() deck.metadata = deck_metadata deck._load_metadata() deck.notes = Note.get_notes_from_collection(collection, deck.anki_dict["id"], deck.metadata.models) direct_children = [child_name for child_name, _ in collection.decks.children(deck.anki_dict["id"]) if Deck.DECK_NAME_DELIMITER not in child_name[len(name) + len(Deck.DECK_NAME_DELIMITER):]] deck.children = seq(direct_children) \ .map(lambda child_name: from_collection(collection, child_name, deck.metadata, True)) \ .filter(lambda it: it is not None).order_by(lambda x: x.anki_dict["name"]).to_list() return deck def from_json(json_dict, deck_metadata=None) -> Deck: """load metadata, load notes, load children""" deck = Deck(NoteModelFileProvider, json_dict) deck._update_fields() deck.metadata = deck_metadata if not deck.metadata: # Todo mental check. The idea is that children don't have metadata deck._load_metadata_from_json(json_dict) deck.deck_config_uuid = json_dict["deck_config_uuid"] deck.notes = [Note.from_json(json_note) for json_note in json_dict["notes"]] deck.children = [from_json(child, deck_metadata=deck.metadata) for child in json_dict["children"]] # Todo should I call this here? deck.post_import_filter() return deck
{ "repo_name": "Stvad/CrowdAnki", "path": "crowd_anki/representation/deck_initializer.py", "copies": "1", "size": "1851", "license": "mit", "hash": 3882468793330620000, "line_mean": 36.02, "line_max": 103, "alpha_frac": 0.6882766072, "autogenerated": false, "ratio": 3.2703180212014136, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4458594628401414, "avg_score": null, "num_lines": null }
from functional_tests.base import FunctionalTest from selenium.common.exceptions import NoSuchElementException from django.contrib.auth.models import Group from accounts.tests.test_models import create_new_user class AdminTest(FunctionalTest): fixtures = [ 'groups_permissions', ] def setUp(self): super(AdminTest, self).setUp() user = create_new_user() user.is_superuser = True user.save() self.user = user def test_admin_page_superuser(self): # Alice logs in self.doLogin(user=self.user) # She sees the admin button in the top navigation bar and clicks on it self.clickUserMenu(self.user) navbar = self.findBy('class_name', 'top-bar') navbar.find_element_by_link_text('Administration').click() column_1 = self.findBy('id', 'column_1') user_module = self.findBy('id', 'module_1', base=column_1) user_module.find_element_by_link_text('Users') configurations_module = self.findBy('id', 'module_3', base=column_1) configurations_module.find_element_by_link_text('Projects') with self.assertRaises(NoSuchElementException): column_1.find_element_by_id('module_6') column_1.find_element_by_id('module_7') def test_admin_page_translators(self): user = create_new_user(id=2, email='foo@bar.com') user.groups.add(Group.objects.filter(name='Translators').first()) user.save() # Alice logs in self.doLogin(user=user) # She sees the admin button in the top navigation bar and clicks on it self.clickUserMenu(user) navbar = self.findBy('class_name', 'top-bar') navbar.find_element_by_link_text('Administration').click() column_1 = self.findBy('id', 'column_1') with self.assertRaises(NoSuchElementException): column_1.find_element_by_id('module_2') column_1.find_element_by_id('module_6') def test_admin_page_wocat_secretariat(self): user = create_new_user(id=2, email='foo@bar.com') user.groups.add(Group.objects.filter(name='WOCAT Secretariat').first()) user.save() # Alice logs in self.doLogin(user=user) # She sees the admin button in the top navigation bar and clicks on it self.clickUserMenu(user) navbar = self.findBy('class_name', 'top-bar') navbar.find_element_by_link_text('Administration').click() # She sees that she can edit projects in the admin section self.findBy('xpath', '//h2[contains(text(), "Configuration")]') self.findBy('xpath', '//strong[contains(text(), "Projects")]') # She clicks to add a new project and sees that she can edit the ID as # well self.findBy('xpath', '//a[contains(@href, "/admin/configuration/project' '/add/")]').click() textfields = self.findManyBy('xpath', '//input[@type="text"]') self.assertEqual(len(textfields), 2) # She goes back to the admin page self.browser.execute_script("window.history.go(-1)") # She can no longer edit institutions (they are managed in the CMS) self.findByNot('xpath', '//strong[contains(text(), "Institutions")]')
{ "repo_name": "CDE-UNIBE/qcat", "path": "functional_tests/test_administration.py", "copies": "1", "size": "3302", "license": "apache-2.0", "hash": 4416484708703444500, "line_mean": 36.5227272727, "line_max": 80, "alpha_frac": 0.6302241066, "autogenerated": false, "ratio": 3.624588364434687, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9754111011999895, "avg_score": 0.0001402918069584736, "num_lines": 88 }
from functional_tests.context import * class ResetPasswordTestCase(LiveServerTestCase): def create_user(self): user = User.objects.create_user('Lisa', 'daisychain_lisa@testingmail.org', 'hunter22') EmailAddress.objects.create(user=user, email='daisychain_lisa@testingmail.org', primary=True, verified=True) user.save() def setUp(self): self.browser = webdriver.Chrome() self.create_user() self.browser.implicitly_wait(3) # Set reCaptcha to Testing-Mode os.environ['NORECAPTCHA_TESTING'] = 'True' def tearDown(self): self.browser.implicitly_wait(300) self.browser.quit() def test_reset_available_execute_done(self): self.browser.get( self.live_server_url + reverse('account_reset_password')) self.assertNotIn('Not Found', self.browser.page_source) self.assertIn('Password Reset', self.browser.page_source) email_box = self.browser.find_element_by_id('id_email') email_box.send_keys('daisychain_lisa@testingmail.org') self.browser.find_element_by_xpath('//button[@type="submit"]').click() self.assertNotIn('Not Found', self.browser.page_source) self.assertIn(('We have sent you an e-mail. Please contact us if you ' 'do not receive it within a few minutes.'), self.browser.page_source) # The email has been sent. self.assertEqual(len(mail.outbox), 1) def test_reset_available_execute_done_with_fakemail(self): self.browser.get( self.live_server_url + reverse('account_reset_password')) self.assertNotIn('Not Found', self.browser.page_source) self.assertIn('Password Reset', self.browser.page_source) email_box = self.browser.find_element_by_id('id_email') email_box.send_keys('dummy@foo.com') self.browser.find_element_by_xpath('//button[@type="submit"]').click() self.assertNotIn('Not Found', self.browser.page_source) self.assertIn(('We have sent you an e-mail. Please contact us if you ' 'do not receive it within a few minutes.'), self.browser.page_source) # The email has been sent. self.assertEqual(len(mail.outbox), 0)
{ "repo_name": "daisychainme/daisychain", "path": "daisychain/functional_tests/test_user_password_reset.py", "copies": "1", "size": "2506", "license": "mit", "hash": 3924837258693107000, "line_mean": 40.7666666667, "line_max": 78, "alpha_frac": 0.5873902634, "autogenerated": false, "ratio": 4.108196721311476, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5195586984711476, "avg_score": null, "num_lines": null }
from functional_tests.context import * class UseradminTestCase(LiveServerTestCase): def create_user(self): user = User.objects.create_user('Lisa', 'lisa@example.org', 'password', is_active=True) user.is_staff = True user.save() EmailAddress.objects.create(user=user, email='lisa@example.org', primary=True, verified=True) user = User.objects.create_user('Alice', 'alice@example.org', 'password', is_active=True) user.save() EmailAddress.objects.create(user=user, email='alice@example.org', primary=True, verified=True) user = User.objects.create_user('Bob', 'bob@example.org', 'password', is_active=True) user.save() EmailAddress.objects.create(user=user, email='bobcd @example.org', primary=True, verified=True) def setUp(self): self.browser = webdriver.Chrome() self.browser.implicitly_wait(3) self.create_user() def tearDown(self): self.browser.quit() def test_useradmin_table(self): # load page self.browser.get(self.live_server_url + '/useradmin/') # should see a login page self.browser.find_element_by_name('login') self.browser.find_element_by_name('password') # force login for Lisa who is staff self.client.force_login(User.objects.get(username="Lisa")) cookie = self.client.cookies['sessionid'] self.browser.add_cookie({'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/'}) self.browser.refresh() self.browser.get(self.live_server_url + '/useradmin/') # make sure the page is there self.assertNotIn('Not Found', self.browser.page_source) # Lisa should see everything self.browser.find_element_by_css_selector('table') td = self.browser.find_element_by_css_selector( 'table tr:nth-child(2) td:first-child') self.assertEqual(td.text, 'Lisa') td = self.browser.find_element_by_css_selector( 'table tr:nth-child(2) td:nth-child(4)') self.assertEqual(td.text, 'lisa@example.org') td = self.browser.find_element_by_css_selector( 'table tr:nth-child(3) td:first-child') self.assertEqual(td.text, 'Alice') td = self.browser.find_element_by_css_selector( 'table tr:nth-child(3) td:nth-child(4)') self.assertEqual(td.text, 'alice@example.org') td = self.browser.find_element_by_css_selector( 'table tr:nth-child(4) td:first-child') self.assertEqual(td.text, 'Bob') td = self.browser.find_element_by_css_selector( 'table tr:nth-child(4) td:nth-child(4)') self.assertEqual(td.text, 'bob@example.org') # logout Lisa self.client.logout() # force login for Alice who is NOT staff self.client.force_login(User.objects.get(username="Alice")) cookie = self.client.cookies['sessionid'] self.browser.add_cookie({'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/'}) self.browser.refresh() self.browser.get(self.live_server_url + '/useradmin/') # detect the custom 403 page td = self.browser.find_element_by_css_selector('div.error-template')
{ "repo_name": "daisychainme/daisychain", "path": "daisychain/functional_tests/test_user_admin.py", "copies": "1", "size": "4196", "license": "mit", "hash": -2477395260152530400, "line_mean": 38.5849056604, "line_max": 76, "alpha_frac": 0.4930886559, "autogenerated": false, "ratio": 4.402938090241343, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 106 }
from functional_tests.factory import ArticleFactory from functional_tests.factory import CategoryFactory from functional_tests.factory import PhotoAlbumSlideFactory from functional_tests.factory import TalkingAlbumSlideFactory class DataSetup(): def create_article(self, title, author, category, location, image, show_modular_content=False, modular_content=None): if modular_content is not None: return ArticleFactory.create(title=title, authors=(author,), categories=(category,), locations=(location,), featured_image=image, show_modular_content=show_modular_content, modular_content=modular_content ) return ArticleFactory.create(title=title, authors=(author,), categories=(category,), locations=(location,), featured_image=image, show_modular_content=show_modular_content ) def create_video_article(self, title, author, location, image): category = CategoryFactory.create(name="VideoZone", slug="videozone", order=16) return self.create_article(title, author, category, location, image) def create_talking_album(self, image): talking_slide = TalkingAlbumSlideFactory.create(image=image) return talking_slide.page def create_photo_album(self, image): photo_slide = PhotoAlbumSlideFactory.create(image=image) return photo_slide.page
{ "repo_name": "PARINetwork/pari", "path": "functional_tests/data_setup.py", "copies": "1", "size": "1589", "license": "bsd-3-clause", "hash": -7386534778447801000, "line_mean": 50.2580645161, "line_max": 115, "alpha_frac": 0.6324732536, "autogenerated": false, "ratio": 4.701183431952662, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002418397792591647, "num_lines": 31 }
from functional_tests import FunctionalTest, ROOT, USERS import time class TestLoginPage (FunctionalTest): def setUp(self): # John opens his browser and goes to the home-page of the tukker app self.url = ROOT + '/default/user/login' get_browser=self.browser.get(self.url) time.sleep(1) def test_put_values_in_login_form(self): username = self.browser.find_element_by_name("username") username.send_keys(USERS['USER2']) password = self.browser.find_element_by_name("password") password.send_keys(USERS['PASSWORD2']) submit_button = self.browser.find_element_by_css_selector("#submit_record__row input") submit_button.click() time.sleep(1) welcome_message = self.browser.find_element_by_css_selector(".flash") self.assertIn('Welcome to Net Decision Making', welcome_message.text) #self.assertEqual(u'Welcome to Net Decision Making\n\xd7', welcome_message.text)
{ "repo_name": "NewGlobalStrategy/NetDecisionMaking", "path": "fts/test_login.py", "copies": "1", "size": "1029", "license": "mit", "hash": 5371855891279311000, "line_mean": 40.16, "line_max": 94, "alpha_frac": 0.6472303207, "autogenerated": false, "ratio": 3.7282608695652173, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48754911902652176, "avg_score": null, "num_lines": null }
from ..functionbase import SSAFunctionBase from ..ssa_types import SSA_OBJECT class BaseOp(SSAFunctionBase): has_side_effects = False def __init__(self, parent, arguments, makeException=False): super(BaseOp, self).__init__(parent, arguments) self.rval = None self.outException = None if makeException: self.outException = parent.makeVariable(SSA_OBJECT, origin=self) def getOutputs(self): return self.rval, self.outException def removeOutput(self, var): outs = self.rval, self.outException assert var is not None and var in outs self.rval, self.outException = [(x if x != var else None) for x in outs] def replaceOutVars(self, vardict): self.rval, self.outException = map(vardict.get, (self.rval, self.outException)) # Given input constraints, return constraints on outputs. Output is (rval, exception) # With None returned for unused or impossible values. This should only be defined if it is # actually implemented. # def propagateConstraints(self, *cons):
{ "repo_name": "orneryhippo/saturdays", "path": "Krakatau-master/Krakatau/Krakatau/ssa/ssa_ops/base.py", "copies": "4", "size": "1087", "license": "apache-2.0", "hash": 8408803330075731000, "line_mean": 35.2333333333, "line_max": 94, "alpha_frac": 0.6826126955, "autogenerated": false, "ratio": 4.025925925925926, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6708538621425926, "avg_score": null, "num_lines": null }
from function_details import FunctionDetails from quadruple import * # # Semantic anaĺysis and structures # ################# # Semantic Cube # ################# # Operator values # 1: + # 2: - # 3: * # 4: / # 5: % # 6: = # 7: == # 8: > # 9: < # 10: <= # 11: >= # 12: <> # 13: && # 14: || # Cube declaration # -1 as return value used for errors # 0-indexed dimentions not used to avoid extra logic with type translation semantic_cube = [[[-1 for i in range(15)] for j in range(6)] for i in range(6)] # First index is for first operand # Second index is for second operand # Third index is for binary operator specified in comment above # Only operations that doesn't return errors are defined # Integer operations semantic_cube[1][1][1] = 1 # int + int = int semantic_cube[1][1][2] = 1 # int - int = int semantic_cube[1][1][3] = 1 # int * int = int semantic_cube[1][1][4] = 2 # int / int = float semantic_cube[1][1][5] = 2 # int % int = float semantic_cube[1][1][6] = 1 # int = int = int semantic_cube[1][2][1] = 2 # int + float = float semantic_cube[1][2][2] = 2 # int - float = float semantic_cube[1][2][3] = 2 # int * float = float semantic_cube[1][2][4] = 2 # int / float = float semantic_cube[1][2][5] = 2 # int % float = float semantic_cube[1][2][6] = 1 # int = float = int semantic_cube[1][1][7] = 4 # int == int = bool semantic_cube[1][1][8] = 4 # int > int = bool semantic_cube[1][1][9] = 4 # int < int = bool semantic_cube[1][1][10] = 4 # int <= int = bool semantic_cube[1][1][11] = 4 # int >= int = bool semantic_cube[1][1][12] = 4 # int <> int = bool # Float operations semantic_cube[2][2][1] = 2 # float + float = float semantic_cube[2][2][2] = 2 # float - float = float semantic_cube[2][2][3] = 2 # float * float = float semantic_cube[2][2][4] = 2 # float / float = float semantic_cube[2][2][5] = 2 # float % float = float semantic_cube[2][2][6] = 2 # float = float = float semantic_cube[2][1][1] = 2 # float + int = float semantic_cube[2][1][2] = 2 # float - int = float semantic_cube[2][1][3] = 2 # float * int = float semantic_cube[2][1][4] = 2 # float / int = float semantic_cube[2][1][5] = 2 # float % int = float semantic_cube[2][1][6] = 2 # float = int = float semantic_cube[2][2][7] = 4 # float == float = bool semantic_cube[2][2][8] = 4 # float > float = bool semantic_cube[2][2][9] = 4 # float < float = bool semantic_cube[2][2][10] = 4 # float <= float = bool semantic_cube[2][2][11] = 4 # float >= float = bool semantic_cube[2][2][12] = 4 # float <> float = bool # Boolean operations semantic_cube[4][4][6] = 4 # bool = bool = bool semantic_cube[4][4][7] = 4 # bool == bool = bool semantic_cube[4][4][8] = 4 # bool > bool = bool semantic_cube[4][4][9] = 4 # bool < bool = bool semantic_cube[4][4][10] = 4 # bool <= bool = bool semantic_cube[4][4][11] = 4 # bool >= bool = bool semantic_cube[4][4][12] = 4 # bool <> bool = bool ################### # Data structures # ################### current_scope = 'global' current_type = '' current_id = '' current_params_types = [] current_params_ids = [] current_function = { 'id' : '', 'type' : '', 'params_types' : [], 'params_ids' : [], 'mem_needed' : [] } # Variables dictionary with scope variables = { 'global' : { }, 'function' : { } } # Functions dictionary functions = {} # Constants dictionary constants = {} # Function call parameters fun_call_params = [] # Current function call auxiliar variable current_fun_call = '' # Translation of types to int int_types = { 'int' : 1, 'float' : 2, 'str' : 3, 'bool' : 4, 'void' : 5, 'error' : -1 } # Translation of types to string string_types = {v: k for k, v in int_types.items()} operations = { '+' : 1, '-' : 2, '*' : 3, '/' : 4, '%' : 5, '=' : 6, '==' : 7, '>' : 8, '<' : 9, '<=' : 10, '>=' : 11, '<>' : 12, '&&' : 13, '||' : 14, '(' : 15, ')' : 16, 'goto' : 17, 'gotof' : 18, 'gotoz' : 19, 'READ' : 20, 'WRITE' : 21, 'RET' : 22, # Return value 'EPROC' : 23, # End Procedure 'EPROG' : 24, # End Program 'DIM' : 25, # Substract value of given quadruple by one (used for repeat only) 'PARAM' : 26, 'gosub' : 27, 'ERA' : 28, 'VERIFY': 29 } inverse_operations = {v: k for k, v in operations.items()} ##################### # Memory management # ##################### # Memory counters per data type # int, float, string, bool global_mem_counter = [0, 1500, 3000, 4500] constants_mem_counter = [6000, 7500, 9000, 10500] function_mem_counter = [12000, 13500, 15000, 16500] # Temporals array might not be needed # temporals_mem_counter = [18000, 19500, 21000, 22500] # Actual Memory # Lists of list, each list consisting of data types # Sublist 0: int, 1: float, 2: string, 3: bool global_memory = [[] for i in range(4)] constants_memory = [[] for i in range(4)] function_memory = [[] for i in range(4)] # Function that resets virtual memory counters # And adds to function details memory needed def reset_mem_counter(cf): global function_mem_counter, current_function current_function = cf # Get memory needed per data type for current function memory_needed = [function_mem_counter[0] - 12000, function_mem_counter[1] - 13500, function_mem_counter[2] - 15000, function_mem_counter[3] - 16500] # Set memory needed per data type for current function functions[current_function['id']].mem_needed = memory_needed # print('Current function: ', current_function['id'], ' needs: ', memory_needed) # print(functions[current_function['id']].mem_needed) # Reset function memory counters function_mem_counter[0] = 12000 function_mem_counter[1] = 13500 function_mem_counter[2] = 15000 function_mem_counter[3] = 16500 # Given scope and data type of variable, return corresponding virtual memory index def get_var_mem(scope, vtype, r=1): r = r - 1 if(scope == 'global'): # Condition to check which counter should be accessed if(vtype == 'int'): # Condition to check which index should be modified global_mem_counter[0] += 1+r # Add one to memory counter plus whatever the array size is if(global_mem_counter[0] > 1499): # Check if too many variables print('Memory Exceeded.') exit(0) # Too many variables return global_mem_counter[0] - 1-r # Return virtual memory position elif(vtype == 'float'): global_mem_counter[1] += 1+r if(global_mem_counter[1] > 2999): print('Memory Exceeded.') exit(0) return global_mem_counter[1] - 1-r elif(vtype == 'string'): global_mem_counter[2] += 1+r if(global_mem_counter[2] > 4499): print('Memory Exceeded.') exit(0) return global_mem_counter[2] - 1-r elif(vtype == 'bool'): global_mem_counter[3] += 1+r if(global_mem_counter[3] > 5999): print('Memory Exceeded.') exit(0) return global_mem_counter[3] - 1-r else: # If it's not global, then we don't care about the scope. We know it's a function if(vtype == 'int'): # Conditionto check which index should be modified function_mem_counter[0] += 1+r # Add one to memory counter if(function_mem_counter[0] > 13499): # Check if too many variables print('Memory Exceeded.') exit(0) # Too many variables return function_mem_counter[0] - 1-r # Return virtual memory position elif(vtype == 'float'): function_mem_counter[1] += 1+r if(function_mem_counter[1] > 14999): print('Memory Exceeded.') exit(0) return function_mem_counter[1] - 1-r elif(vtype == 'string'): function_mem_counter[2] += 1+r if(function_mem_counter[2] > 16499): print('Memory Exceeded.') exit(0) return function_mem_counter[2] - 1-r elif(vtype == 'bool'): function_mem_counter[3] += 1+r if(function_mem_counter[3] > 17999): print('Memory Exceeded.') exit(0) return function_mem_counter[3] - 1-r # add a constant and return its memory address def append_const(cons, cons_type): if(cons_type == 'int'): # Condition to check which index should be modified constants_mem_counter[0] += 1 # Add one to memory counter if(constants_mem_counter[0] > 7499): # Check if too many variables print('Memory Exceeded.') exit(0) # Too many variables constants_memory[0].append(cons) return constants_mem_counter[0] - 1 # Return virtual memory position elif(cons_type == 'float'): constants_mem_counter[1] += 1 if(constants_mem_counter[1] > 8999): print('Memory Exceeded.') exit(0) constants_memory[1].append(cons) return constants_mem_counter[1] - 1 elif(cons_type == 'string'): constants_mem_counter[2] += 1 if(constants_mem_counter[2] > 10499): print('Memory Exceeded.') exit(0) constants_memory[2].append(cons) return constants_mem_counter[2] - 1 elif(cons_type == 'bool'): constants_mem_counter[3] += 1 if(constants_mem_counter[3] > 11999): print('Memory Exceeded.') exit(0) constants_memory[3].append(cons) return constants_mem_counter[3] - 1 def get_operand_mem(op, cf): current_function = cf var_mem = None if op in variables['function'][current_function['id']]: var_det = variables['function'][current_function['id']][op] var_mem = var_det.vmemory elif op in variables['global']: # if op[0] == '_': # # TODO: Generate new local tmp variable with return value of function # # and generate quadruple to assign the current value of global variable to tmp variable # global_var_det = variables['global'][op] # global_var_type = global_var_det.vtype # global_var_mem = global_var_det.vmemory # var_mem = get_var_mem('function', global_var_type) # tmpQuad = Quadruple() # tmpQuad.build(operations['='], global_var_mem, None, var_mem) # else: var_det = variables['global'][op] var_mem = var_det.vmemory else: print('Undefined variable ', op) exit(0) return var_mem def memory_to_data_type(mem): if((mem >= 0 and mem < 1500) or (mem >= 6000 and mem < 7500) or (mem >= 12000 and mem < 13500)): return 'int' elif((mem >= 1500 and mem < 3000) or (mem >= 7500 and mem < 9000) or (mem >= 13500 and mem < 15000)): return 'float' elif((mem >= 3000 and mem < 4500) or (mem >= 9000 and mem < 10500) or (mem >= 15000 and mem < 16500)): return 'str' else: return 'bool' ###################### # Semantic functions # ###################### #################### # Helper Functions # #################### def typeString(s): return s.split("'")[1]
{ "repo_name": "chelord21/zmeya", "path": "semantics.py", "copies": "1", "size": "10738", "license": "mit", "hash": 4227730548324032000, "line_mean": 30.1217391304, "line_max": 95, "alpha_frac": 0.5963490733, "autogenerated": false, "ratio": 3.0581031045286244, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.904366803253008, "avg_score": 0.02215682905970884, "num_lines": 345 }
from function.discrete_function import DiscreteFunction class Permutation(DiscreteFunction): """ Permutation class. Defines permutation over objects given a well defined domain for the objects, and and array of array of obbjects that specify the permutation itself. Note: We use right-hand functional behavior, i.e. p1 * p2[i] = p1(p2[i]). So, evaluation of 'multiplied' permutations is from right to left. """ def __init__(self, p_domain, cycles): """ Create a permutation given: :param p_domain: The set of ALL elements that are members of the permutation. :param cycles: The permutation itself, an array of array of domain elements. """ Permutation.check_cycles(p_domain, cycles) self.__cycles = Permutation.normalize(p_domain, cycles) DiscreteFunction.__init__(self, Permutation.generate_init_map(p_domain, self.cycles)) @property def cycles(self): return self.__cycles def inverse(self): # reverse all the cycles r_cycles = list() for cycle in reversed(self.cycles): r_cycle = [x for x in reversed(cycle)] r_cycles.append(r_cycle) return Permutation(self.domain, r_cycles) def __mul__(self, other): # self on left cycles = list(self.cycles) cycles.extend(other.cycles) return Permutation(self.domain, cycles) def __rmul__(self, other): # self on right cycles = list(other.cycles) cycles.extend(self.cycles) return Permutation(self.domain, cycles) @staticmethod def check_cycles(domain, cycles): if not isinstance(cycles, list): raise Exception('Cycles must be a list not {0}.'.format(type(list))) for cycle in cycles: if not isinstance(cycle, list): raise Exception('Cycle must be a list not {0}.'.format(type(list))) # all elements in domain? not_in_domain = {x for x in cycle if x not in domain} if len(not_in_domain) > 0: raise Exception('Elements in cycle {0} must be in domain.'.format(cycle)) # any duplicates? seen = set() twice_seen = {x for x in cycle if x in seen or seen.add(x)} if len(twice_seen) > 0: raise Exception('Duplicate elements in cycle {0}.'.format(cycle)) @staticmethod def normalize(domain, cycles): seen = set() new_cycles = list() for v in domain: if v in seen: continue new_cycle = list() start = v new_cycle.append(v) seen.add(v) while True: v = Permutation.apply(cycles, v) if v == start: break new_cycle.append(v) seen.add(v) new_cycles.append(new_cycle) return new_cycles @staticmethod def apply(cycles, x): for cycle in cycles[::-1]: x = Permutation.apply_cycle(cycle, x) return x @staticmethod def apply_cycle(cycle, x): i = cycle.index(x) if x in cycle else None if i is None: return x next_index = i + 1 if i < len(cycle) - 1 else 0 return cycle[next_index] @staticmethod def generate_init_map(domain, cycles): init_map = dict() for x in domain: y = Permutation.apply(cycles, x) init_map[x] = y return init_map def __getitem__(self, key): return self.apply(self.cycles, key) def __setitem__(self, key, value): raise Exception('Cannot set elements once a permuation is created.') def __delattr__(self, item): raise Exception('Cannot delete elements once a permutation is created.') def __str__(self): tcycles = [] for c in self.cycles: tcycles.append('[{0}]'.format(', '.join(str(x) for x in c))) txt = ', '.join(x for x in tcycles) return '[{0}]'.format(txt)
{ "repo_name": "dpazel/music_rep", "path": "function/permutation.py", "copies": "1", "size": "4090", "license": "mit", "hash": -1861439734318872300, "line_mean": 31.9838709677, "line_max": 110, "alpha_frac": 0.5706601467, "autogenerated": false, "ratio": 4.148073022312373, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.000906984534322903, "num_lines": 124 }
from function.function_pitch_range import FunctionPitchRange from function.piecewise_linear_function import PiecewiseLinearFunction from tonalmodel.diatonic_pitch import DiatonicPitch class PiecewiseLinearPitchFunction(PiecewiseLinearFunction, FunctionPitchRange): def __init__(self, transition_points=list(), restrict_domain=False): tp = PiecewiseLinearPitchFunction._translate_transition_points(transition_points) PiecewiseLinearFunction.__init__(self, tp, restrict_domain) FunctionPitchRange.__init__(self, self) @staticmethod def _translate_transition_points(transition_points): tps = list() for tp in transition_points: if isinstance(tp[1], str): diatonic_pitch = DiatonicPitch.parse(tp[1]) elif isinstance(tp[1], DiatonicPitch): diatonic_pitch = tp[1] else: raise Exception('Illegal type \'{0}\' for diatonic pitch {1}'.format(type(tp[1]), tp[1])) tps.append((tp[0], diatonic_pitch.chromatic_distance)) return tps
{ "repo_name": "dpazel/music_rep", "path": "function/piecewise_linear_pitch_function.py", "copies": "1", "size": "1087", "license": "mit", "hash": 7876933537157331000, "line_mean": 34.064516129, "line_max": 105, "alpha_frac": 0.6752529899, "autogenerated": false, "ratio": 3.9816849816849818, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9990342688941819, "avg_score": 0.033319056528632505, "num_lines": 31 }
from function import Function from frame import Frame import collections import operator import textwrap import dis import sys class VirtualMachineError(Exception): pass Block = collections.namedtuple('Block', 'type, handler, stack_height') class VirtualMachine(object): def __init__(self): self.frames = [] self.frame = None self.return_value = None self.last_exception = None def run_code(self, code, global_names=None, local_names=None): frame = self.make_frame(code, global_names=global_names, local_names=local_names) self.run_frame(frame) def make_frame(self, code, callargs={}, global_names=None, local_names=None): if global_names is not None and local_names is not None: local_names = global_names elif self.frames: global_names = self.frame.global_names else: global_names = local_names = { '__builtins__': __builtins__, '__name__': '__main__', '__doc__': None, '__package__': None, } local_names.update(callargs) frame = Frame(code, global_names, local_names, self.frame) return frame def push_frame(self, frame): self.frames.append(frame) self.frame = frame def pop_frame(self): self.frames.pop() if self.frames: self.frame = self.frames[-1] else: self.frame = None def run_frame(self, frame): self.push_frame(frame) while True: byte_name, arguments = self.parse_byte_and_args() why = self.dispatch(byte_name, arguments) while why and frame.block_stack: why = self.manage_block_stack(why) if why: break self.pop_frame() if why == 'exception': exc, val, tb = self.last_exception e = exc(val) e.__traceback__ = tb raise e return self.return_value def top(self): return self.frame.stack[-1] def pop(self): return self.frame.stack.pop() def push(self, *vals): self.frame.stack.extend(vals) def popn(self, n): if n: ret = self.frame.stack[-n:] self.frame.stack[-n:] = [] return ret else: return [] def parse_byte_and_args(self): f = self.frame opoffset = f.last_instruction bytecode = f.code_obj.co_code[opoffset] f.last_instruction += 1 byte_name = dis.opname[bytecode] if bytecode >= dis.HAVE_ARGUMENT: arg = f.code_obj.co_code[f.last_instruction:f.last_instruction+2] f.last_instruction += 2 arg_val = arg[0] + (arg[1] * 256) if bytecode in dis.hasconst: arg = f.code_obj.co_consts[arg_val] elif bytecode in dis.hasname: arg = f.code_obj.co_names[arg_val] elif bytecode in dis.haslocal: arg = f.code_obj.co_varnames[arg_val] elif bytecode in dis.hasjrel: arg = f.last_instruction + arg_val else: arg = arg_val argument = [arg] else: argument = [] return byte_name, argument def dispatch(self, byte_name, argument): why = None try: bytecode_fn = getattr(self, 'byte_%s' % byte_name, None) if bytecode_fn is None: if byte_name.startswith('UNARY_'): self.unaryOperator(byte_name[6:]) elif byte_name.startswith('BINARY_'): self.binaryOperator(byte_name[7:]) else: raise VirtualMachineError( 'unsupported bytecode type: %s' % byte_name ) else: why = bytecode_fn(*argument) except: self.last_exception = sys.exc_info()[:2] + (None,) why = 'exception' return why def push_block(self, b_type, handler=None): stack_height = len(self.frame.stack) self.frame.block_stack.append(Block(b_type, handler, stack_height)) def pop_block(self): return self.frame.block_stack.pop() def unwind_block(self, block): if block.type == 'except-handler': offset = 3 else: offset = 0 while len(self.frame.stack) > block.stack_height + offset: self.pop() if block.type == 'except-handler': traceback, value, exctype = self.popn(3) self.last_exception = exctype, value, traceback def manage_block_stack(self, why): frame = self.frame block = frame.block_stack[-1] if block.type == 'loop' and why == 'continue': self.jump(self.return_value) why = None return why self.pop_block() self.unwind_block(block) if block.type == 'loop' and why == 'break': why = None self.jump(block.handler) return why if block.type in ['setup-except', 'finally'] and why == 'exception': self.push_block('except-handler') exctype, value, tb = self.last_exception self.push(tb, value, exctype) self.push(tb, value, exctype) why = None self.jump(block.handler) return why elif block.type == 'finally': if why in ('return', 'continue'): self.push(self.return_value) self.push(why) why = None self.jump(block.handler) return why return why def jump(self, jump): self.frame.last_instruction = jump def byte_LOAD_CONST(self, const): self.push(const) def byte_POP_TOP(self): self.pop() def byte_LOAD_NAME(self, name): frame = self.frame if name in frame.local_names: val = frame.local_names[name] elif name in frame.global_names: val = frame.global_names[name] elif name in frame.builtin_names: val = frame.builtin_names[name] else: raise NameError("name '%s' is not defined" % name) self.push(val) def byte_STORE_NAME(self, name): self.frame.local_names[name] = self.pop() def byte_LOAD_FAST(self, name): if name in self.frame.local_names: val = self.frame.local_names[name] else: raise UnboundLocalError("local variable '%s' referenced before assignment" % name) self.push(val) def byte_STORE_FAST(self, name): self.frame.local_names[name] = self.pop() def byte_LOAD_GLOBAL(self, name): f = self.frame if name in f.global_names: val = f.global_names[name] elif name in f.builtin_names: val = f.builtin_names[name] else: raise NameError("global name '%s' is not defined" % name) self.push(val) BINARY_OPERATORS = { 'POWER': pow, 'MULTIPLY': operator.mul, 'FLOOR_DIVIDE': operator.floordiv, 'TRUE_DIVIDE': operator.truediv, 'MODULO': operator.mod, 'ADD': operator.add, 'SUBTRACT': operator.sub, 'SUBSCR': operator.getitem, 'LSHIFT': operator.lshift, 'RSHIFT': operator.rshift, 'AND': operator.and_, 'XOR': operator.xor, 'OR': operator.or_, } def binaryOperator(self, op): x, y = self.popn(2) self.push(self.BINARY_OPERATORS[op](x, y)) COMPARE_OPERATORS = [ operator.lt, operator.le, operator.eq, operator.ne, operator.gt, operator.ge, lambda x, y: x in y, lambda x, y: x not in y, lambda x, y: x is y, lambda x, y: x is not y, lambda x, y: issubclass(x, Exception) and issubclass(x, y), ] def byte_COMPARE_OP(self, opnum): x, y = self.popn(2) self.push(self.COMPARE_OPERATORS[opnum](x, y)) def byte_LOAD_ATTR(self, attr): obj = self.pop() val = getattr(obj, attr) self.push(val) def byte_STORE_ATTR(self, name): val, obj = self.popn(2) setattr(obj, name, val) def byte_BUILD_LIST(self, count): elts = self.popn(counts) self.push(elts) def byte_BUILD_MAP(self, size): self.push({}) def byte_STORE_MAP(self): the_map, val, key = self.popn(3) the_map[key] = val self.push(the_map) def byte_LIST_APPEND(self, count): val = self.pop() the_list = self.frame.stack[-count] the_list.append(val) def byte_JUMP_FORWARD(self, jump): self.jump(jump) def byte_JUMP_ABSOLUTE(self, jump): self.jump(jump) def byte_POP_JUMP_IF_TRUE(self, jump): val = self.pop() if val: self.jump(jump) def byte_POP_JUMP_IF_FALSE(self, jump): val = self.pop() if not val: self.jump(jump) def byte_SETUP_LOOP(self, dest): self.push_block('loop', dest) def byte_GET_ITER(self): self.push(iter(self.pop())) def byte_FOR_ITER(self, jump): iterobj = self.top() try: v = next(iterobj) self.push(v) except StopIteration: self.pop() self.jump(jump) def byte_BREAK_LOOP(self): return 'break' def byte_POP_BLOCK(self): self.pop_block() def byte_MAKE_FUNCTION(self, argc): name = self.pop() code = self.pop() defaults = self.popn(argc) globs = self.frame.global_names fn = Function(name, code, globs, defaults, None, self) self.push(fn) def byte_CALL_FUNCTION(self, argc): lenKw, lenPos = divmod(argc, 256) posargs = self.popn(lenPos) func = self.pop() frame = self.frame retval = func(*posargs) self.push(retval) def byte_RETURN_VALUE(self): self.return_value = self.pop() return 'return' # Example of how to use the bytecode interpreter txt = """\ def loop(): x = 1 while x < 5: x = x + 1 return x print(loop()) """ code = textwrap.dedent(txt) code = compile(code, "<%s>" % __name__, "exec", 0, 1) #dis.dis(code) vm = VirtualMachine() vm.run_code(code)
{ "repo_name": "tylersco/Python2Python", "path": "virtualmachine.py", "copies": "1", "size": "10538", "license": "mit", "hash": 570452782093542400, "line_mean": 26.6587926509, "line_max": 94, "alpha_frac": 0.5357752894, "autogenerated": false, "ratio": 3.726308345120226, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.975778387157696, "avg_score": 0.0008599525886531049, "num_lines": 381 }
from .function import Function from .numbers import nan class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as Python's: the remainder always has the same sign as the divisor. Examples ======== >>> x**2 % y x**2%y >>> _.subs({x: 5, y: 6}) 1 """ @classmethod def eval(cls, p, q): from .add import Add from .mul import Mul from .numbers import Integer from .exprtools import gcd_terms from ..polys.polytools import gcd def doit(p, q): """Try to return p % q if both are numbers or +/-p is known to be less than or equal q. """ if p.is_infinite or q.is_infinite: return nan if (p == q or p == -q or p.is_Pow and p.exp.is_Integer and p.base == q or p.is_integer and q == 1): return Integer(0) if q.is_Number: if p.is_Number: return p % q if q == 2: if p.is_even: return Integer(0) elif p.is_odd: return Integer(1) # by ratio r = p/q try: d = int(r) except TypeError: pass else: rv = p - d*q if (rv*q).is_nonnegative: return rv elif (rv*q).is_nonpositive: return rv + q # by difference d = p - q if d.is_negative: if q.is_negative: return d elif q.is_positive: return p rv = doit(p, q) if rv is not None: return rv # denest if isinstance(p, cls): # easy qinner = p.args[1] if qinner == q: return p # XXX other possibilities? # extract gcd; any further simplification should be done by the user G = gcd(p, q) if G != 1: p, q = [ gcd_terms(i/G, clear=False, fraction=False) for i in (p, q)] pwas, qwas = p, q # simplify terms # (x + y + 2) % x -> Mod(y + 2, x) if p.is_Add: args = [] for i in p.args: a = cls(i, q) if a.count(cls) > i.count(cls): args.append(i) else: args.append(a) if args != list(p.args): p = Add(*args) else: # handle coefficients if they are not Rational # since those are not handled by factor_terms # e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y) cp, p = p.as_coeff_Mul() cq, q = q.as_coeff_Mul() ok = False if not cp.is_Rational or not cq.is_Rational: r = cp % cq if r == 0: G *= cq p *= int(cp/cq) ok = True if not ok: p = cp*p q = cq*q # simple -1 extraction if p.could_extract_minus_sign() and q.could_extract_minus_sign(): G, p, q = [-i for i in (G, p, q)] # check again to see if p and q can now be handled as numbers rv = doit(p, q) if rv is not None: return rv*G # put 1.0 from G on inside if G.is_Float and G == 1: p *= G return cls(p, q, evaluate=False) elif G.is_Mul and G.args[0].is_Float and G.args[0] == 1: p = G.args[0]*p G = Mul._from_args(G.args[1:]) return G*cls(p, q, evaluate=(p, q) != (pwas, qwas)) def _eval_is_integer(self): p, q = self.args if p.is_integer and q.is_integer and q.is_nonzero: return True def _eval_is_nonnegative(self): p, q = self.args if p.is_real and q.is_real and q.is_positive: return True def _eval_is_nonpositive(self): p, q = self.args if p.is_real and q.is_real and q.is_negative: return True
{ "repo_name": "skirpichev/omg", "path": "diofant/core/mod.py", "copies": "1", "size": "4357", "license": "bsd-3-clause", "hash": 1994197438779773000, "line_mean": 27.477124183, "line_max": 77, "alpha_frac": 0.4353913243, "autogenerated": false, "ratio": 3.8219298245614035, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9757321148861404, "avg_score": 0, "num_lines": 153 }
from function import Function from sympy.core.numbers import Float from sympy.core.function import expand_mul class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as python's: the remainder always has the same sign as the divisor. Examples ======== >>> from sympy.abc import x, y >>> x**2 % y Mod(x**2, y) >>> _.subs({x: 5, y: 6}) 1 """ nargs = 2 @classmethod def eval(cls, p, q): from sympy.simplify.simplify import nsimplify if q.is_Number: float = not q.is_Rational pnew = expand_mul(p) if pnew.is_Number: float = float or not pnew.is_Rational if not float: return pnew % q return Float(nsimplify(pnew) % nsimplify(q)) elif pnew.is_Add and pnew.args[0].is_Number: r, p = pnew.as_two_terms() p += Mod(r, q) return Mod(p, q, evaluate=False)
{ "repo_name": "ichuang/sympy", "path": "sympy/core/mod.py", "copies": "3", "size": "1089", "license": "bsd-3-clause", "hash": -1995028766297333800, "line_mean": 26.9230769231, "line_max": 77, "alpha_frac": 0.5610651974, "autogenerated": false, "ratio": 3.794425087108014, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001221001221001221, "num_lines": 39 }
from function import Function from sympy.core.numbers import Float from sympy.core.function import expand_mul class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as python's: the remainder always has the same sign as the divisor. Examples ======== >>> from sympy.abc import x, y >>> x**2 % y Mod(x**2, y) >>> _.subs({x: 5, y: 6}) 1 """ nargs = 2 @classmethod def eval(cls, p, q): from sympy.simplify.simplify import nsimplify if q.is_Number: float = not q.is_Rational pnew = expand_mul(p) if pnew.is_Number: float = float or not pnew.is_Rational if not float: return pnew % q return Float(nsimplify(pnew) % nsimplify(q)) elif pnew.is_Add and pnew.args[0].is_Number: r, p = pnew.as_two_terms() p += Mod(r, q) return Mod(p, q, evaluate=False)
{ "repo_name": "amitjamadagni/sympy", "path": "sympy/core/mod.py", "copies": "1", "size": "1090", "license": "bsd-3-clause", "hash": -2918974266267994600, "line_mean": 26.25, "line_max": 77, "alpha_frac": 0.5605504587, "autogenerated": false, "ratio": 3.797909407665505, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9858459866365505, "avg_score": 0, "num_lines": 40 }
from function import * #from function import restart_comm import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) FRONT_C = 1 LEFT_C = 2 RIGHT_C = 3 BACK_C = 4 #Switch Case that selects the commands def command(x): bytes = x.split() #Motor Commands if bytes[0] == 'w': move_forward(bytes) if bytes[0] == 'a': move_left(bytes) if bytes[0] == 's': move_reverse(bytes) if bytes[0] == 'd': move_right(bytes) if bytes[0] == 'x': stop() if bytes[0] == 'q': rotate_counter(bytes) if bytes[0] == 'e': rotate_clockwise(bytes) #Calibration and Distance Commands if bytes[0] == 'm': encoder_calibration(int(bytes[1]), int(bytes[2]))#Byte one(1 for Y and 2 for X), Byte Two(quantity of test) if bytes[0] == 'M': encoder_update() if bytes[0] == 'K': encoder_reset() if bytes[0] == 'B': encoder_update() encoder_current_value() if bytes[0] == 'H': encoder_constant_value() #regarding side, 1 is for positive direction, while 2 is for negative directions if bytes[0] == 'X': move_x(bytes[1], bytes[2])#side, speed if bytes[0] == 'Y': move_y(bytes[1], bytes[2]) #Sensor Commands if bytes[0] == 'u': print(us_sensor()) if bytes[0] == 'o':#reading the values of the capacitor sensor capacitor_sensor() if bytes[0] == 'h': capacitor_hard_reset() if bytes[0] == 'l': capacitor_calibration() if bytes[0] == 'v': print(capacitor_block_identity())#0 wire, 1 no wire no insulation, 2 insulation if bytes[0] == 'L': capacitor_calibrate_move(int(bytes[1]), int(bytes[2]), int(bytes[3])) if bytes[0] == 'V': capacitor_block_multiple(int(bytes[1])) #Quantity of test #Servo Command if bytes[0] == 't': servo_top(bytes[1]) if bytes[0] == 'b': servo_bottom(bytes[1]) if bytes[0] == 'n': servo_info() if bytes[0] == 'c': servo_change(bytes) if bytes[0] == 'p': servo_bottom(bytes[1]) sleep(5) servo_top(bytes[1]) #Communicatin Command if bytes[0] == 'R': restart_comm() if bytes[0] == 'C': clear_comm() """ Raspberry Pi Gyro Commands #Gyro Commands if bytes[0] == 'W': move_gyro(FRONT_C, bytes[1], bytes[2]) if bytes[0] == 'A': move_gyro(LEFT_C, bytes[1], bytes[2]) if bytes[0] == 'D': move_gyro(RIGHT_C, bytes[1], bytes[2]) if bytes[0] == 'S': move_gyro(LEFT_C, bytes[1], bytes[2]) if bytes[0] == 'Q': rotate_counter_gyro() if bytes[0] == 'E': rotate_clockwise_gyro() if bytes[0] == 'P': redefine_pre() if bytes[0] == 'F': redefine_fre(bytes[1]) if bytes[0] == 'I': redefine_sensa(bytes[1]) if bytes[0] == 'T':#testing redefine_pre() gyro_main() #Magnetometer Commands if bytes[0] == 'N': north() """ #Arduino Gyro Commands """ if bytes[0] == 'I': gyro_cali() if bytes[0] == 'A': gyro_update_angle() if bytes[0] == 'R': gyro_report_angle() """ return #Here is the loop that recieves input from the user print("Welcome to The Raspberry Pi Controller HQ") print("FRONT: 1, LEFT: 2, RIGHT: 3, BACK: 4") print("Variable Speed: [direction (wasd) and x to stop] [Left A] [Left B] [Right A] [Right B]") print("Move by axes and block: [direction (XY)] [positive or negative] [motor speed] [number of block] ") print("Servo: FRONT = 1 BACK = 4 --> [up(t) or down(b) or pick_up(p)] [servo#]") print("Gyro: [direction (caps motor's keys)] [max_speed] [gryo_sensativity]") print("Communication Commands: [command (R or C)]") print("Ultrasonic Sensor: 'u' ") restart_comm() clear_comm() stop() assign_side() #servo_top() while(True): x = input("Enter Command: ") print(x) if x == '1': end() break else: command(x) GPIO.cleanup()
{ "repo_name": "STMU-IEEE/Robotics-16-17", "path": "commWithArduino.py", "copies": "1", "size": "3556", "license": "mit", "hash": 4971638669412967000, "line_mean": 23.3561643836, "line_max": 109, "alpha_frac": 0.6223284589, "autogenerated": false, "ratio": 2.4490358126721765, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.35713642715721766, "avg_score": null, "num_lines": null }
from Function import * from Math import * from Area import * import random class distributionObject(mathObject): def __init__(self): self.type = "distribution" self.e = 0 self.s = 0 def cal(self, val): pass def val(self): pass class PointDistribution(distributionObject): def __init__(self, point): self.value = point self.e = self.value self.s = 0 def cal(self, val): if val == self.value: return 1 else: return 0 def val(self): return self.value class BernoulliDistribution(distributionObject): def __init__(self, p): self.p = p self.e = p self.s = 1 - p def cal(self, val): if val == 1: return p elif val == 0: return 1 - p else: return None def val(self): p = random.random() if p > self.p: return 0 else: return 1 class BinomialDistribution(distributionObject): def __init__(self, p, n): self.p = p self.n = n self.e = n * p self.s = n * p * (1 - p) self.innerFunc = binomialDisFunction(n, p) def cal(self, k): return self.func.cal(k) def val(self): rlt = 0 for i in xrange(self.n): tmp = random.random() if tmp <= p: rlt += 1 return rlt class GeometricDistribution(distributionObject): def __init__(self, p): self.p = p self.e = 1 / p self.s = (1 - p) / p / p def cal(self, k): return (1 - p) ** (k - 1) * p def val(self): rlt = 0 while random.random() > self.p: rlt += 1 return rlt class PossionDistribution(distributionObject): def __init__(self, fy): self.fy = fy self.e = fy self.s = fy def cal(self, k): return (self.fy ** k) * (math.exp( (-1) * self.fy )) / math.factorial(k) def val(self): rlt = 0 tmp = self.fy while tmp > 0: pos = random.random() if pos <= tmp: tmp -= pos rlt += 1 else: tmp = 0 return rlt class UniformDistribution(distributionObject): def __init__(self, a, b): self.a = a self.b = b self.e = (a + b) / 2 self.s = ((b - a) ** 2) / 12 def cal(self, top, bottom): return (top - bottom) / (self.b - self.a) def val(self): return math.uniform(self.a, self.b) class NormalDistribution(distributionObject): def __init__(self, mu, sigma): self.mu = mu self.sigma = sigma self.e = mu self.s = sigma ** 2 self.innerFunc = GaussianFunction(mu, sigma) def cal(self, x): return self.innerFunc.cal(x) def val(self): delta = math.sqrt(abs( (-1) * 2 * (self.sigma ** 2) * ( 0.5 * math.log(2 * np.pi * (self.sigma ** 2)) + math.log(random.random()) ) )) return delta + self.mu # When I feel that I should add sth. here, I'll add it.
{ "repo_name": "Anon-LeoH/UncleDaLearn", "path": "UD/Distribution/__init__.py", "copies": "1", "size": "3179", "license": "mit", "hash": -6411330354054800000, "line_mean": 22.204379562, "line_max": 142, "alpha_frac": 0.4869455804, "autogenerated": false, "ratio": 3.5719101123595505, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.455885569275955, "avg_score": null, "num_lines": null }
from function import * # # [0]A [1]B [2]C [3]D [4]E [5]F [6]G # +-----+-----+-----+-----+-----+-----+-----+ #[6]| | | | | | | | # 1 | | | | | | | | # | | | | | | | | # +-----------------------------------------+ #[5]| | | | | | | | # 2 | | | | | | | | # | | | | | | | | # +-----------------------------------------+ #[4]| | | | | | | | # 3 | | | | | | | | # | | | | | | | | # +-----------------------------------------+ #[3]| | | | | | | | # 4 | | | | | | | | # | | | | | | | | # +-----------------------------------------+ #[2]| | | | | | | | # 5 | | | | | | | | # | | | | | | | | # +-----------------------------------------+ #[1]| | | | | | | | # 6 | | | | | | | | # | | | | | | | | # +-----------------------------------------+ #[0]|START| | | | | | | # 7 | X | | | | | | | # |HE RE| | | | | | | # +-----+-----+-----+-----+-----+-----+-----+ import numpy as np # from heapq import * blocked_vals = {-1} # this is a list of the possible blocked values for pathfinding purposes my_location = (0,0) # first val for vert, second for horiz (row, col) default_path = np.array( [0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6], [1,6],[1,5],[1,4],[1,3],[1,2],[1,1],[1,0], [2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6], [3,6],[3,5],[3,4],[3,3],[3,2],[3,1],[3,0], [4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6], [5,6],[5,5],[5,4],[5,3],[5,2],[5,1],[5,0], [6,0],[6,1],[6,2],[6,3],[6,4],[6,5],[6,6] ) my_path=default_path world_map = np.full((7,7), 8, dtype=np.int) # unexplored blocks will have a travel cost value of 8. # this travel cost will be reduced to 1 when the robot explores that region. flow_map = [] def follow(path, globalPath): while path: if my_location == path[0]: path = np.delete(path,0); # if we have reached the next location, remove it from the path. if world_map[my_location[0]][my_location[1]]<1: world_map[my_location[0]][my_location[1]]=1 # run sensors and \ get_sensors(my_location) # update surrounding nodes if world_map[path[0][0]][path[0][1]] in blocked_vals: path = np.delete(path,0); # if my next point is blocked, move on to the next point in the path. # update the map here flow_map = flowField(world_map, path[0]) travel_direction = flow_map[my_location[0],my_location[1]] if travel_direction[0] > 0: # if we need to move north move_north() elif travel_direction[0] < 0: # if we need to move south move_south() elif travel_direction[1] > 0: # if we need to move west move_west() else: # else move east move_east() def you_are_here(): #for debug purposes view_map = world_map view_map[my_location[0]][my_location[1]] = 'X' print(view_map) def dist(a, b): return ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) **.5 def flowField(world, target): output_field = np.zeros((7,7,2), dtype=np.int) neighbor_dirs = [(0,1),(0,-1),(1,0),(-1,0)] closed_set = set() parents = {} g_score = {start:0} open_set = set() # list of nodes to be explored open_set.add(target) while open_set: my_loc = open_set.pop(0) for i,j in neighbor_dirs: neighbor = my_loc[0] + i, my_loc[1] + j if 0 <= neighbor[0] < world.shape[0]: if 0 <= neighbor[1] <= world.shape[1]: if world[neighbor[0]][neighbor[1]] not in blocked_vals: open_set.add(neighbor) g_score[neighbor] = g_score[my_loc] + world[neighbor[0]][neighbor[1]] else: continue g_score[neighbor] = -1 else: continue else: continue return output_field def move_north(): move_y(1,1) return def move_south(): move_y(2,1) return def move_east(): move_x(1,1) return def move_west(): move_x(2,1) return def get_sensors(location): block_direction = us_sensor() print(block_direction) current_block_identity = capacitor_block_identity() print(current_block_identity) #Ultrasonic function return values #0: no near by block # North 1000 # South 100 # East 10 # West 1 #Example of multiple blocks: North and South: #1100 #Capacitor function return values #-1 -> Warning retake value #0-> tunnel #1-> dead_ends #2-> Insulation world_map[my_location[0]][my_location[1]] = current_block_identity if(block_direction[0] == 1):#North world_map[my_location[0]+1][my_location[1]] = -1; elif(block_direction[1] == 1):#South world_map[my_location[0]-1][my_location[1]] = -1; elif(block_direction[2] == 1):#East world_map[my_location[0]][my_location[1]+1] = -1; elif(block_direction[3] == 1):#West world_map[my_location[0]][my_location[1]-1] = -1; return
{ "repo_name": "STMU-IEEE/Robotics-16-17", "path": "Pathfinding.py", "copies": "1", "size": "5404", "license": "mit", "hash": -8849045695402046000, "line_mean": 34.0909090909, "line_max": 107, "alpha_frac": 0.4287564767, "autogenerated": false, "ratio": 2.8427143608627037, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3771470837562704, "avg_score": null, "num_lines": null }
from Function_Module import * from BMaster_code import * import sys def main(cpath, Type, N=6): overview = path(cpath,'Overview.txt') pyomo_code = False if Type in ('S', 'Test'): GG = .02 pyomo_code = True elif Type == 'M': GG = .15 elif Type == 'L': GG = .30 else: GG = None pyomo_code = True (BS, BT, HS), HT = Hybrid_code(cpath, N=N, GG=GG) print if Pyomo_code: PS, PT = BM_wrapper(cpath) print line('#',10) tee_print(overview,'RESULTS [Bhanu]: ',t=0, n=0) tee_print(overview,'MEAN: {0:.2f} seconds'.format(mean(BT)),t=1, n=0) tee_print(overview,'STDEV: {0:.2f} seconds'.format(stdev(BT)),t=1, n=0) tee_print(overview,'MIN: {0:.2f} seconds'.format(min(BT)),t=1, n=0) tee_print(overview,'MAX: {0:.2f} seconds'.format(max(BT)),t=1, n=1) tee_print(overview,'MEAN: ' + curr(mean(BS)),t=1, n=0) tee_print(overview,'STDEV: ' + curr(stdev(BS)),t=1, n=0) tee_print(overview,'ERROR: ' + perr(stdev(BS),mean(BS)),t=1, n=0) tee_print(overview,'MIN: ' + curr(min(BS)),t=1, n=0) tee_print(overview,'MAX: ' + curr(max(BS)),t=1, n=2) tee_print(overview,'RESULTS [Bhanu]: ',t=0, n=0) tee_print(overview,'TIME: {0:.2f} seconds'.format(sum(BT)),t=1, n=0) tee_print(overview,'OBJ: ' + curr(min(BS)),t=1, n=1) tee_print(overview,'RESULTS [Hybrid]: ',t=0, n=0) tee_print(overview,'TIME: {0:.2f} seconds'.format(HT),t=1, n=0) tee_print(overview,'OBJ: ' + curr(HS),t=1, n=1) if Pyomo_code: tee_print(overview,'RESULTS [Pyomo]: ',t=0, n=0) tee_print(overview,'TIME: {0:.2f} seconds'.format(PT),t=1, n=0) tee_print(overview,'OBJ: ' + curr(PS),t=1, n=2) tee_print(overview,'COMPARISON [Bhanu vs Hybrid]: ',t=0, n=0) comp_err = perr(min(BS)-HS,HS) tee_print(overview,'ERROR: ' + comp_err,t=1, n=0) speedup = '{0:.2f}'.format( (HT - sum(BT)) / sum(BT) ) tee_print(overview,'SPEEDUP: ' + speedup,t=1, n=1) if Pyomo_code: tee_print(overview,'COMPARISON [Hybrid vs Pyomo]: ',t=0, n=0) comp_err = perr(HS-PS,PS) tee_print(overview,'ERROR: ' + comp_err,t=1, n=0) speedup = '{0:.2f}'.format( (PT - HT) / HT ) tee_print(overview,'SPEEDUP: ' + speedup,t=1, n=2) _, BI = argmin(BS) I_path = path(cpath,'Bhanu_Results') #I_path = path(cpath,'Instance_{}'.format(BI + 1)) Best_path = path(cpath,'Best_Instance') cp('{0}/Solution_{1}.txt', '{0}/Best_Solution.txt'.format(I_path, BI + 1)) print line('#',10) + '\n' if '__main__' == __name__: try: Type = sys.argv[1] except IndexError: Type = 'Misc' ID = 'M' + Type + '_' + id_generator(size=4) if Type in ('S','M','L', 'Test'): cpath = 'Results/{}/Results_{}'.format(Type, ID) else: cpath = 'Results/{}/Results_{}'.format('Misc', ID) overview = path(cpath,'Overview.txt') print ID main(cpath, Type) rm('WITP*txt*')
{ "repo_name": "cdhagmann/WITP", "path": "Master.py", "copies": "1", "size": "3006", "license": "apache-2.0", "hash": -7043722281118619000, "line_mean": 32.032967033, "line_max": 78, "alpha_frac": 0.5532268796, "autogenerated": false, "ratio": 2.5154811715481173, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.35687080511481173, "avg_score": null, "num_lines": null }
from Function_Module import * from coopr.pyomo import * from coopr import neos from coopr.opt import SolverFactory import coopr.environ import os import time from PyomoCode.ReferenceTechModel import Pyomo_tech def solve_tech_model(idx, solver='gurobi', time=None, gap=None, cutoff=None): tech = 'Tech{}'.format(idx) bash_command('rm -f ReferenceModel*') model = Pyomo_tech(idx) instance = model.create() # instance.write('model_{}.lp'.format(idx),symbolic_solver_labels=True) opt = SolverFactory(solver) if gap is not None: if gap < 1: opt.options["MIPGap"] = gap else: opt.options["MIPGapAbs"] = gap if time is not None: opt.options["TimeLimit"] = time if cutoff is not None: opt.options["Cutoff"] = cutoff with open('temp.log', 'w') as f: with Redirect(f, f): results = opt.solve(model, tee=True) status = results['Solver'][0]['Termination condition'].key transformed_results = instance.update_results(results) # print 'After Loading: {}'.format(status) if status == 'optimal': instance.load(results) rm('temp.log') obj = instance.Total_Cost_Objective() SubCost(tech, instance, obj) # FTI = [tech, instance.alpha_put.value, instance.alpha_pick.value] #print '\tFinished {0:6}: {1}, {2}'.format(*FTI) #FTI = [tech, instance.lambda_put.value/8., instance.lambda_pick.value/8.] #print '\tFinished {0:6}: {1:6} | {2:6}'.format(*FTI) with open('results_{}.txt'.format(idx), 'w') as f: f.write('Results from {}\n'.format(tech)) f.write('Putaway Technology: {}\n'.format(instance.lambda_put.value)) f.write('Picking Technology: {}\n\n'.format(instance.lambda_pick.value)) with Redirect(f, f): display(instance) else: obj = 'Cutoff Error' with open('results_{}.yml'.format(idx), 'w') as f: from check_sol import T f.write('Results from {}\n'.format(tech)) f.write('Putaway Technology: {}\n'.format(T[idx][0])) f.write('Picking Technology: {}\n'.format(T[idx][1])) if status == 'optimal': f.write('Total_Cost_Objective:\n\tValue={}\n\n'.format(obj)) else: f.write('Total_Cost_Objective:\n\tValue={}\n\n'.format(status)) with Redirect(f, f): transformed_results.write() bash_command('rm -f ReferenceModel*') return tech, instance, obj ''' Run Pyomo on each I x J subproblem and returns the best.''' def Pyomo_code(**kwargs): T_setup = 'gc.enable()\nfrom Pyomo_code import solve_tech_model' Times = [] Techs = [] Obj = [] indices = sorted(reversed(range(36)), key=lambda k: k % 6, reverse=True) indices = kwargs.get('indices', indices) output = kwargs.get('output', True) cutoff = kwargs.get('cutoff', False) def T_command(idx, **kwargs): opts = {} time_limit = int( min([max( [P_timeout / len(indices), 2 * 3600] ), 12 * 3600]) ) time_limit = 48 * 60 * 60 opts['S'] = kwargs.get('solver', 'gurobi') opts['T'] = kwargs.get('time', time_limit) opts['I'] = idx opts['G'] = kwargs.get('gap', None) if cutoff and Obj: if min(Obj) == float('inf'): opts['C'] = None else: if 0 <= opts['G'] < 1: if min(Obj) * opts['G'] <= 1000: opts['G'] = 1000 opts['C'] = min(Obj) # + opts['G'] * 2 else: opts['C'] = min(Obj) # * (1 + 1.5 * opts['G']) else: opts['C'] = min(Obj) # + opts['G'] * 2 opts['T'] = kwargs.get('time', min([max(Times) * 5000, time_limit])) else: opts['C'] = None args = "{I}, solver='{S}', time={T}, gap={G}, cutoff={C}".format(**opts) return 'solve_tech_model({})'.format(args) for i, idx in enumerate(indices): if i > 0: if sum(Times) + mean(Times) > P_timeout: raise Exception prog = (i + 1) / float(len(indices)) tech = 'Tech{}'.format(idx) command = T_command(idx, **kwargs) T = Timeit(command, setup=T_setup) obj = read_P_sol('results_{}.yml'.format(idx)) Times.append(T) Techs.append(tech) if type(obj) == str: if obj == 'maxTimeLimit': line = bash_command('tail -1 temp.log')[0] obj = float(line.split()[2].strip(',')) err = float(line.split()[-1].strip('%')) Obj.append(obj) info = [tech, '{} [{}%]'.format(curr(obj), err), curr(min(Obj)), perc(prog), ptime(T)] else: Obj.append(float('inf')) if min(Obj) == float('inf'): info = [tech, obj, obj, perc(prog), ptime(T)] else: info = [tech, obj, curr(min(Obj)), perc(prog), ptime(T)] else: Obj.append(obj) info = [tech, curr(obj), curr(min(Obj)), perc(prog), ptime(T)] print "\tFinished {0:6}: {1} ({2}) [{3} Completed] ({4})".format(*info) with open('results_summary.txt', 'a') as f: f.write("Finished {0:6}: {1} ({2}) [{3} Completed] ({4})\n".format(*info)) print '' OBJ = min(Obj) if OBJ == float('inf'): info = ['None', obj, ptime(sum(Times))] else: idx = Obj.index(OBJ) TECH = Techs[idx] info = [TECH, curr(OBJ), ptime(sum(Times))] cp('results_{}.yml'.format(num_strip(TECH)), 'results_best.yml') cp('summary_{}.txt'.format(num_strip(TECH)), 'summary_best.txt') print "\tOptimal Solution {}: {} ({})".format(*info) with open('results_summary.txt', 'a') as f: f.write("\nOptimal Solution:\n\t{}: {} ({})".format(*info)) command = 'rm -f ReferenceModel*' _ = bash_command(command) if output and not cutoff: L = zip(Techs, Obj) L.sort(key=lambda (t, o): o) print '\nTop 5 Techs:' for t, o in L[:5]: print '\t{0:6}: {1}'.format(t, curr(o)) return OBJ, sum(Times) P_timeout = 7 * 24 * 60 * 60 def read_P_sol(sol_file): with open(sol_file, 'r') as f: try: while 'Total_Cost_Objective' not in next(f): pass try: val = next(f).split('=')[1].strip() ans = float(val) except ValueError: if val == 'infeasible': ans = 'Infeasible' elif val == 'minFunctionValue': ans = 'Cutoff Error' else: ans = val except StopIteration: ans = 'Unknown Error' finally: return ans def tech_test(idx, t=None, gap=None): print time.strftime("%a, %d %b %Y %I:%M:%S %p") solve_tech_model(idx, time=t, gap=gap) print time.strftime("%a, %d %b %Y %I:%M:%S %p") def SubCost(tech, inst, obj): idx = num_strip(tech) PickingCost = inst.C_alpha.value * inst.alpha_pick.value PickingCost += inst.C_beta.value * sum(inst.beta_pick[t].value for t in inst.TIMES) PutawayCost = inst.C_alpha.value * inst.alpha_put.value PutawayCost += inst.C_beta.value * sum(inst.beta_put[t].value for t in inst.TIMES) MHECost = sum(inst.MHE.value * (inst.alpha_put.value + inst.beta_put[t].value) for t in inst.TIMES) PutawayTechCost = inst.C_put.value PickingTechCost = inst.C_pick.value WhBasicInvCost = sum(inst.C_hp[p] * inst.y_pt[p, t].value for p in inst.PRODUCTS for t in inst.TIMES) WhFashionInvCost = sum(inst.C_hq[q] * inst.X_osq[s, q] * inst.tau_sq[s, q].value for s in inst.STORES for q in inst.FASHION) StoreBasicInvCost = sum(inst.C_hsp[s, p] * inst.y_spt[s, p, t].value for s in inst.STORES for p in inst.PRODUCTS for t in inst.TIMES) StoreFashionInvCost = sum(inst.C_hsq[s, q] * inst.y_sqt[s, q, t].value for s in inst.STORES for q in inst.FASHION for t in inst.TIMES) BasicInbCost = sum(inst.C_fv[v] * inst.n_vt[v, t].value for v in inst.VENDORS_P for t in inst.TIMES) BasicInbCost += sum(inst.C_vv[v] * inst.W_p[p] * inst.x_vpt[v, p, t].value for v, p in inst.OMEGA_P for t in inst.TIMES) FashionInbCost = sum(inst.C_fv[v] * inst.n_vt[v, t].value for v in inst.VENDORS_Q for t in inst.TIMES) FashionInbCost += sum(inst.C_vv[v] * inst.W_q[q] * inst.X_ivq[v, q] * inst.rho_vqt[v, q, t].value for v, q in inst.OMEGA_Q for t in inst.TIMES) OutboundCost = sum(inst.C_fs[s] * inst.n_st[s, t].value for s in inst.STORES for t in inst.TIMES) OutboundCost += sum(inst.C_vs[s] * inst.W_p[p] * inst.x_spt[s, p, t].value for s in inst.STORES for p in inst.PRODUCTS for t in inst.TIMES) OutboundCost += sum(inst.C_vs[s] * inst.W_q[q] * inst.X_osq[s, q] * inst.rho_sqt[s, q, t].value for s in inst.STORES for q in inst.FASHION for t in inst.TIMES) with open('summary_{}.txt'.format(idx), 'w') as f: from check_sol import T f.write('Results from {}\n'.format(tech)) f.write('Putaway Technology: {}\n'.format(T[idx][0])) f.write('Picking Technology: {}\n\n'.format(T[idx][1])) f.write('Full-Time Putaway workers: {}\n'.format(inst.alpha_put.value)) f.write('Full-Time Picking workers: {}\n'.format(inst.alpha_pick.value)) f.write('\nCost Breakdown:\n') f.write('\tMHECost {}\n'.format(curr(MHECost))) f.write('\tPutawayTechCost {}\n'.format(curr(PutawayTechCost))) f.write('\tPickingTechCost {}\n'.format(curr(PickingTechCost))) f.write('\tWhBasicInvCost {}\n'.format(curr(WhBasicInvCost))) f.write('\tBasicInbCost {}\n'.format(curr(BasicInbCost))) f.write('\tWhFashionInvCost {}\n'.format(curr(WhFashionInvCost))) f.write('\tFashionInbCost {}\n'.format(curr(FashionInbCost))) f.write('\tPutawayCost {}\n'.format(curr(PutawayCost))) f.write('\tStoreBasicInvCost {}\n'.format(curr(StoreBasicInvCost))) f.write('\tStoreFashionInvCost {}\n'.format(curr(StoreFashionInvCost))) f.write('\tOutboundCost {}\n'.format(curr(OutboundCost))) f.write('\tPickingCost {}\n'.format(curr(PickingCost))) f.write('\tTotal {}\n'.format(curr(obj))) with Redirect(f, f): print '\n\nPrinting New Fashion Solution:\n' ri = lambda num: int(round(num, 0)) print 'Inbound Fashion Solution' for v, q in sorted(inst.OMEGA_Q): print num_strip(v), '\t', print num_strip(q), '\t', for t in sorted(inst.TIMES): if inst.rho_vqt[v, q, t] == 1: print t, '\t', ri(inst.X_ivq[v, q]) print '\nOutbound Solution' for s in sorted(inst.STORES): for q in sorted(inst.FASHION): print num_strip(s), '\t', print num_strip(q), '\t', for t in sorted(inst.TIMES): if inst.rho_sqt[s, q, t] == 1: print t, '\t', ri(inst.X_osq[s, q]) print '\nStore Inventory' for s in sorted(inst.STORES): print 'Store{}'.format(num_strip(s)) for q in sorted(inst.FASHION): print num_strip(v), for t in sorted(inst.TIMES): num = ri(inst.y_sqt[s, q, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nShipments from (Basic) Vendor to Warehouse' for v in sorted(inst.VENDORS_Q): for t in sorted(inst.TIMES): num = ri(inst.n_vt[v, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nPrinting New Basic Solution:\n' print '\nInbound Solution' for v, p in sorted(inst.OMEGA_P): for t in sorted(inst.TIMES): print num_strip(v), '\t', print num_strip(p), '\t', print t, '\t', print ri(inst.x_vpt[v, p, t].value) print '\nOutbound Solution' for s in sorted(inst.STORES): print 'Store{}'.format(num_strip(s)) for p in sorted(inst.PRODUCTS): print num_strip(p), for t in sorted(inst.TIMES): num = ri(inst.x_spt[s, p, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nWarehouse Inventory' for p in sorted(inst.PRODUCTS): print num_strip(p), for t in sorted(inst.TIMES): num = ri(inst.y_pt[p, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nStore Inventory' for s in sorted(inst.STORES): print 'Store{}'.format(num_strip(s)) for p in sorted(inst.PRODUCTS): print num_strip(p), for t in sorted(inst.TIMES): num = ri(inst.y_spt[s, p, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nShipments from (Basic) Vendor to Warehouse' for v in sorted(inst.VENDORS_P): for t in sorted(inst.TIMES): num = ri(inst.n_vt[v, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nShipments from (Fashion) Vendor to Warehouse' for v in sorted(inst.VENDORS_Q): for t in sorted(inst.TIMES): num = ri(inst.n_vt[v, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nShipments from Warehouse to Stores' for s in sorted(inst.STORES): print num_strip(s), for t in sorted(inst.TIMES): num = ri(inst.n_st[s, t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nNo of part-time putaway workers:' for t in sorted(inst.TIMES): num = ri(inst.beta_put[t].value) print str(num) + (' ' * (10 - len(str(num)))), print print '\nNo of part-time picking workers:' for t in sorted(inst.TIMES): num = ri(inst.beta_pick[t].value) print str(num) + (' ' * (10 - len(str(num)))), print if '__main__' == __name__: T1 = Pyomo_code(gap=.0175) # t, i, o = solve_tech_model(11) # SubCost(t,i,o)
{ "repo_name": "cdhagmann/WITP", "path": "Pyomo_code.py", "copies": "1", "size": "15472", "license": "apache-2.0", "hash": -3691504815902600000, "line_mean": 37.2024691358, "line_max": 102, "alpha_frac": 0.5021975181, "autogenerated": false, "ratio": 3.398198989677136, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44003965077771356, "avg_score": null, "num_lines": null }
from Function_Module import * from Pyomo_code import * from BigMModel import solve_big_m_model import time global_gap = .02 def tech_idx(tup): i, j = tup return (i - 1) * 6 + (j - 1) BIG_M_TIMEOUT = 12 * 60 * 60 @Timer def Bhanu_code(): command = "echo '' | mono WITP-TPH.exe" output = bash_command(command) Last_line = output[-1] assert 'minimum cost' in Last_line S = float(Last_line.split()[-1]) return S @Timer def Hybrid_code(cpath, N, GG=None): T1 = time.time() BS, BT = [], [] count, k, gap = {}, 1, 0 best = set() bi, bj = set(), set() Instance_path = path(cpath,'Bhanu_Results') mkpath(Instance_path) for k in xrange(1, N+1): # Instance_path = cpath #path(cpath,'Instance_{}'.format(k)) # mkpath(Instance_path) print "Instance {} of {}:".format(k, N) S, T = Bhanu_code() qprint('RUN TIME [Bhanu]: ' +ptime(T), t=1) qprint('MIN COST [Bhanu]: ' + curr(S) , t=1, n=1) BT.append(T) BS.append(S) sol_file = '{}/Solution_{}.txt'.format(Instance_path, k) mv('*Sol*', sol_file) with open(sol_file,'r') as f: lines = f.readlines() TC = OrderedSet(tuple(map(int, l.split()[1:3])) for l in lines[-7:-2] if 'None' not in l) bi.add(TC[0][0]) bj.add(TC[0][1]) tech_choices = map(tech_idx, TC) # print tech_choices best.add(tech_choices[0]) for idx, index in enumerate(tech_choices): count[index] = count.get(index, 0) + (len(tech_choices) - idx) if k == 1: cp('TPH.cs', '{}/'.format(Instance_path)) cp('WITP-TPH.exe', '{}/'.format(Instance_path)) cp('WITPdataSet*', '{}/'.format(Instance_path)) L = sorted(count.items(), key=lambda (idx, c): c, reverse=True) ''' for index in L: if len(best) >= 5: break else: best.add(index) ''' #print sorted(list(best), key=lambda i: count[i], reverse=True) #indices = list(idx for idx, c in L[:5]) indices = sorted(list(best), key=lambda i: count[i], reverse=True) print bi print L print bj # print indices global global_gap #global_gap = GG #GG = stdev(BS) * 10 / mean(BS) if GG is None else GG #global_gap = round(min([(GG if GG < 1 else GG/100.), GG_min]), 4) qprint('Optimality Gap: {:.2%}'.format(global_gap)) print qprint("Warm Big M Method:") Instance_path = path(cpath,'WBM_Method') mkpath(Instance_path) HS, HT = solve_big_m_model(PUTAWAY=list(bi), PICKING=list(bj), time_limit=BIG_M_TIMEOUT - (time.time() - T1), gap=global_gap) cp('bigm_output.txt', '{}/'.format(Instance_path)) cp('PyomoCode/Pickled_Data', '{}/'.format(Instance_path)) return BS, BT, HS @Timer def BM_wrapper(cpath): qprint("Big M Benchmark:") Instance_path = path(cpath,'BigM_Benchmark') mkpath(Instance_path) PS, PT = solve_big_m_model(gap=global_gap, time_limit=BIG_M_TIMEOUT) cp('bigm_output.txt', '{}/'.format(Instance_path)) cp('PyomoCode/Pickled_Data', '{}/'.format(Instance_path)) return PS if '__main__' == __name__: ID = 'C' + id_generator(size=5) foldername = 'Results_' + ID overview = path(foldername,'Overview.txt') cpath = path(foldername,'Case_1') print ID (BS, BT, HS), HT = Hybrid_code(cpath, N=6) print ptime(HT) PS, PT = BM_wrapper(cpath) print ptime(PT)
{ "repo_name": "cdhagmann/WITP", "path": "BMaster_code.py", "copies": "1", "size": "3590", "license": "apache-2.0", "hash": -1315937620766560000, "line_mean": 25.204379562, "line_max": 77, "alpha_frac": 0.5498607242, "autogenerated": false, "ratio": 2.9718543046357615, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40217150288357617, "avg_score": null, "num_lines": null }
from Function_Module import * from Pyomo_code import * import time global_gap = .02 def tech_idx(tup): i, j = tup return (i - 1) * 6 + (j - 1) @Timer def Bhanu_code(): command = "echo '' | mono WITP-TPH.exe" output = bash_command(command) Last_line = output[-1] assert 'minimum cost' in Last_line S = float(Last_line.split()[-1]) return S @Timer def Hybrid_code(cpath, N, GG=None): BS, BT = [], [] count, k, gap = {}, 1, 0 best = set() bi, bj = set(), set() Instance_path = path(cpath,'Bhanu_Results') mkpath(Instance_path) for k in xrange(1, N+1): # Instance_path = cpath #path(cpath,'Instance_{}'.format(k)) # mkpath(Instance_path) print "Instance {} of {}:".format(k, N) S, T = Bhanu_code() qprint('RUN TIME [Bhanu]: ' +ptime(T), t=1) qprint('MIN COST [Bhanu]: ' + curr(S) , t=1, n=1) BT.append(T) BS.append(S) sol_file = '{}/Solution_{}.txt'.format(Instance_path, k) mv('*Sol*', sol_file) with open(sol_file,'r') as f: lines = f.readlines() TC = OrderedSet(tuple(map(int, l.split()[1:3])) for l in lines[-7:-2] if 'None' not in l) bi.add(TC[0][0]) bj.add(TC[0][1]) tech_choices = map(tech_idx, TC) # print tech_choices best.add(tech_choices[0]) for idx, index in enumerate(tech_choices): count[index] = count.get(index, 0) + (len(tech_choices) - idx) if k == 1: cp('TPH.cs', '{}/'.format(Instance_path)) cp('WITP-TPH.exe', '{}/'.format(Instance_path)) cp('WITPdataSet*', '{}/'.format(Instance_path)) L = sorted(count.items(), key=lambda (idx, c): c, reverse=True) ''' for index in L: if len(best) >= 5: break else: best.add(index) ''' #print sorted(list(best), key=lambda i: count[i], reverse=True) #indices = list(idx for idx, c in L[:5]) indices = sorted(list(best), key=lambda i: count[i], reverse=True) print bi print L print bj # print indices global global_gap #global_gap = GG #GG = stdev(BS) * 10 / mean(BS) if GG is None else GG #global_gap = round(min([(GG if GG < 1 else GG/100.), GG_min]), 4) qprint('Optimality Gap: {:.2%}'.format(global_gap)) print qprint("Hybrid Method:") Instance_path = path(cpath,'Hybrid_Method') mkpath(Instance_path) HS, _ = Pyomo_code(indices=indices, cutoff=True, gap=global_gap) mv('results_best.yml', '{}/Best_Results.yml'.format(Instance_path)) mv('results_*', '{}/'.format(Instance_path)) mv('summary_*', '{}/'.format(Instance_path)) return BS, BT, HS @Timer def Pyomo_wrapper(cpath): qprint("Pyomo Benchmark:") Instance_path = path(cpath,'Pyomo_Benchmark') mkpath(Instance_path) PS, PT = Pyomo_code(cutoff=True, gap=global_gap) mv('results_best.yml', '{}/Best_Results.yml'.format(Instance_path)) mv('results_*', '{}/'.format(Instance_path)) mv('summary_*', '{}/'.format(Instance_path)) cp('PyomoCode/Pickled_Data', '{}/'.format(Instance_path)) return PS if '__main__' == __name__: ID = 'C' + id_generator(size=5) foldername = 'Results_' + ID overview = path(foldername,'Overview.txt') cpath = path(foldername,'Case_1') print ID (BS, BT, HS), HT = Hybrid_code(cpath, N=6) print #PS, PT = Pyomo_wrapper(cpath)
{ "repo_name": "cdhagmann/WITP", "path": "Master_code.py", "copies": "1", "size": "3573", "license": "apache-2.0", "hash": 1419714023379492900, "line_mean": 25.8646616541, "line_max": 77, "alpha_frac": 0.545200112, "autogenerated": false, "ratio": 3.038265306122449, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4083465418122449, "avg_score": null, "num_lines": null }
from functionrefactor.commands import launch_case from functionrefactor.formatter import Formatter from functionrefactor.settings import * from tests.common_functions import * import json class TestRuns(): def test_runs(self): with open("tests/cases/test_cases.json", "r") as tcf: test_launcher = json.load(tcf) settings.update_global_settings(test_launcher) test_cases = test_launcher["launcher"] for case in test_cases: if case["active"]: [hpp_result, cpp_result] = launch_case("tests/cases",case) self.check_result("tests/cases/" + case["hpp_out"], "tests/cases/" + case["cpp_out"], hpp_result, cpp_result) def check_result(self, hpp_path, cpp_path, hpp_result, cpp_result): clang_formatter = Formatter() hpp_expected_result = clang_formatter.open_and_launch(hpp_path) cpp_expected_result = clang_formatter.open_and_launch(cpp_path) are_equal(hpp_result, hpp_expected_result) are_equal(cpp_result, cpp_expected_result)
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_runs.py", "copies": "1", "size": "1134", "license": "mit", "hash": -1969767511287521000, "line_mean": 35.5806451613, "line_max": 79, "alpha_frac": 0.6234567901, "autogenerated": false, "ratio": 3.78, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49034567901, "avg_score": null, "num_lines": null }
from functionrefactor.header import HeaderDef from functionrefactor.parser import Parser from functionrefactor.formatter import Formatter from functionrefactor.settings import * import sys import os import json __all__ = ['parse_header', 'parse_to_file', 'main'] # def parse_header(filename): parser = Parser() clang_formatter = Formatter() path_name = os.path.splitext(os.path.basename(filename))[0] text = clang_formatter.open_and_launch(filename) it = enumerate(text) header_root = HeaderDef() try: parser.parse_block(it, next(it)[1], header_root) except StopIteration: pass return [ clang_formatter.launch_batch(header_root.get_lines_hpp()), clang_formatter.launch_batch( header_root.get_lines_cpp(path_name + ".hpp")) ] def parse_to_file(filename, hpp_file=None, cpp_file=None): ''' filename: the input header to be processed hpp_file: the output header cpp_file the output cpp file If any of the output hpp/cpp files is emited the parse header will be returned. This is intended for use in testing''' print("parse_to_file: processing %s, output header: %s, output source: %s" % (filename, hpp_file, cpp_file)) [output_hpp, output_cpp] = parse_header(filename) if hpp_file: #hpp_file = _get_full_path('', filename, hpp_file, '.hpp') with open(hpp_file, 'w') as hpp: hpp.writelines(s + '\n' for s in output_hpp) print("header file: %s write done" % (hpp_file)) if cpp_file: #cpp_file = _get_full_path('', filename, cpp_file, '.cpp') with open(cpp_file, 'w') as cpp: cpp.writelines(s + '\n' for s in output_cpp) print("source file: %s write done" % (cpp_file)) if not hpp_file or not cpp_file: return [output_hpp, output_cpp] def launch_cases(jfile_path): ''' runs a sets of cases defined in a json file. It need to include a json key "launcher" ''' print("launching cases") try: with open(jfile_path, "r") as launcher: launcher_file = json.load(launcher) print("laucher file: %s opened" % jfile_path) except FileNotFoundError: print('File not found, file_path: ' + file_path) return settings.update_global_settings(launcher_file) launch_list = launcher_file['launcher'] base_folder = os.path.dirname(launcher.name) if base_folder and len(base_folder) > 0: base_folder = base_folder + sep assert len(launch_list) != 0 for input_key in launch_list: launch_case(base_folder, input_key) def launch_case(base_folder, jobj_case, launch_list=None): if jobj_case['active']: sep = os.path.sep settings.update_case_settings(jobj_case) if jobj_case['overwrite']: return parse_to_file( base_folder + jobj_case['input'], _get_full_path(base_folder, jobj_case['input'], jobj_case['hpp_out'], '.hpp'), _get_full_path(base_folder, jobj_case['input'], jobj_case['cpp_out'], '.cpp')) else: return parse_to_file(base_folder + sep + jobj_case['input']) def _get_full_path(base_folder, input_file, destination, extension): ''' returns the full path for the output file based on the input folder and output directory, taking into account that the output might be an output path or a filename''' print('base_folder: %s, input_file: %s, destination: %s, extension: %s' % (base_folder, input_file, destination, extension)) sep = os.path.sep #the input file may contain folders input_file_dirname = os.path.dirname(input_file) base_folder = base_folder + input_file_dirname input_file = os.path.basename(input_file) # looking for full path or relative path if '.cpp' in destination or '.hpp' in destination: return base_folder + destination + extension else: return base_folder + destination + sep + input_file.replace(".hpp", '') + extension def execute(argv=None): if argv is None: argv = sys.argv main(argv) def main(args): """Entry point for the application script""" print(args) if len(args) <= 1: raise AssertionError elif '.json' in args[1]: launch_cases(args[1]) else: if len(args) == 2: parse_to_file(args[1]) if len(args) == 3: parse_to_file(args[1], args[2]) if len(args) > 3: parse_to_file(args[1], args[2], args[3]) if __name__ == '__main__': main(sys.argv)
{ "repo_name": "astrodroid/functionrefactor", "path": "functionrefactor/commands.py", "copies": "1", "size": "4758", "license": "mit", "hash": 2868219211083006000, "line_mean": 31.3673469388, "line_max": 93, "alpha_frac": 0.6008827238, "autogenerated": false, "ratio": 3.6018168054504165, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4702699529250416, "avg_score": null, "num_lines": null }
from functionrefactor.header import * from functionrefactor.formatter import Formatter from functionrefactor.string_utilities import find_and_replace_all, is_invalid import difflib import sys def is_strictly_equal(actual, expected): assert actual == expected if actual == expected: print("OK! a: " + actual) else: print("missmatch:'" + actual + "' not equal to '" + expected + "'") def remove_whitespace(a): return find_and_replace_all(a, '', '\t', '\n', ' ') def is_equal(actual, expected): actual = remove_whitespace(actual).strip() expected = remove_whitespace(expected).strip() if actual == expected: print("OK! a: " + actual) else: print("missmatch:'" + actual + "' not equal to '" + expected + "'") assert actual == expected def strict_parse_batch_run(input_list, expected_output_hpp, expected_output_cpp, _lamda): it = enumerate(input_list) txt = next(it)[1] result_hpp = [] result_cpp = [] while True: try: h = HeaderDef() pos = _lamda(it, txt, h) result_hpp.append(h.format_hpp()) result_cpp.append(h.format_cpp()) txt = next(it)[1] except StopIteration: break are_equal(result_hpp, expected_output_hpp) are_equal(result_cpp, expected_output_cpp) def parse_batch_run(input_list, expected_output_hpp, expected_output_cpp, _lamda): it = enumerate(input_list) txt = next(it)[1] result_hpp = [] result_cpp = [] while True: try: h = HeaderDef() pos = _lamda(it, txt, h) result_hpp.append(h.format_hpp()) result_cpp.append(h.format_cpp()) txt = next(it)[1] except StopIteration: break are_equal(result_hpp, expected_output_hpp) are_equal(result_cpp, expected_output_cpp) def are_equal(list_actual, list_exp): #removes empty lines list_actual = [x for x in list_actual if not is_invalid(x)] list_exp = [x for x in list_exp if not is_invalid(x)] '''ignores spaces tabs and newlines, on the basis that test errors are too frequent to be of any use. spaces can be easily added when needed from the header.py and header_components.py classes''' diff = difflib.SequenceMatcher(lambda x: x in ['\t', ' ', '\n'], list_actual, list_exp, True) diff_ratio = diff.ratio() if diff_ratio < 0.99: print("Missmatch: diff_ratio: %s " % diff_ratio) sys.stdout.writelines( difflib.unified_diff(list_actual, list_exp, 'result', 'expected')) else: return for a, b in zip(list_actual, list_exp): is_equal(a, b) def are_strictly_equal(list_actual, list_exp): for a, b in zip(list_actual, list_exp): is_strictly_equal(a, b) if len(list_actual) != len(list_exp): print("missmatch_between actual and expected") print(list_actual) print(list_exp) assert len(list_actual) == len(list_exp) def full_regex_match(str, regex): ''' looks if the full match equals to the input string''' assert regex.match(str).group(0) == str def full_regex_search(str, regex, result_str): ''' looks if the full search equals to the result_str''' assert regex.search(str).group(0) == result_str
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/common_functions.py", "copies": "1", "size": "3405", "license": "mit", "hash": 1037333626056094200, "line_mean": 29.1327433628, "line_max": 105, "alpha_frac": 0.6002936858, "autogenerated": false, "ratio": 3.528497409326425, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4628791095126425, "avg_score": null, "num_lines": null }
from functionrefactor.parser import Parser, CommentParser, Regex from functionrefactor.header import * from tests.common_functions import * import pytest def test_comments(): ''' ignores_new lines ''' _in = [ "//comment is this", "/* comment is this as well */", "auto p = get_value(); //some comment", "void main(auto& args);/* single line comment */", "/* multiline comment", "\n", "\n", "\n", "\n", "\n*/ int i = 0;", '' ] expected_result = [ "//comment is this", "/* comment is this as well */", "//some comment", '/* single line comment */', "/* multiline comment*/\n" ] rg = Regex() parser = CommentParser(rg) parse_batch_run(_in, expected_result, [], lambda i, pos, h: parser.parse(i, pos, h)) def test_comments_strict(): _in = [ "auto p = get_value();//some comment", "void main(auto& args);/* multi line\n", "comment */", "/* multiline comment", "\n", "\n", "\n", "\n", "\n*/ int i = 0;", '' ] expected_result = [ "\n//some comment\n", '\n/* multi line\ncomment */\n', "\n/* multiline comment\n\n\n\n\n*/\n", ] rg = Regex() parser = CommentParser(rg) strict_parse_batch_run(_in, expected_result, [], lambda i, pos, h: parser.parse(i, pos, h)) def test_comment_parser(): ''' uses main parse function parse_block which determines what is contained in each line ''' _in = [ "//comment is this\n", "/* comment is this as well */\n", " //some comment\n", "/* single line comment */\n", "/* multiline comment\n", "\n", "\n", "\n", "\n", "\n*/", '' ] expected_result = [ "\n//comment is this\n", "/* comment is this as well */\n", "//some comment\n", "/* single line comment */\n", "/* multiline comment\n", "\n", "\n", "\n", "\n", "\n*/\n" ] parser = Parser() h = HeaderDef() it = enumerate(_in) pos = next(it) try: parser.parse_block(it, pos[1], h) except StopIteration: pass is_equal(h.format_hpp(), ''.join(expected_result))
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_comments.py", "copies": "1", "size": "2164", "license": "mit", "hash": 2117821112919553300, "line_mean": 30.8235294118, "line_max": 92, "alpha_frac": 0.5203327172, "autogenerated": false, "ratio": 3.507293354943274, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4527626072143274, "avg_score": null, "num_lines": null }
from functionrefactor.parser import Parser from functionrefactor.header import * from tests.common_functions import * # yapf: disable _in = [ "#define SMACRO = ()... ; /* */","#define OLDSTYLECONST = 42", r"#define MULTILINE_MACRO = DOSOMETHING()\ ", r" return -1;\ ", "#ifdef SOMETHING", "int do_somethingelse()", " {return v;}", "#else ", " int dont_do_nothing() {return 0;}", "#endif", "#ifdef CONSTANT //This explains something about something ", " std::vector<std::string> text{ }", "#endif", '' ] expected_result_hpp = [ "#define SMACRO = ()... ; /* */", "#define OLDSTYLECONST = 42", r"#define MULTILINE_MACRO = DOSOMETHING()\ ", r" return -1;\ ","" "#ifdef SOMETHINGint do_somethingelse();#else int dont_do_nothing();#endif", "#ifdef CONSTANT //This explains something about somethingstd::vector<std::string> text{ }#endif" ] expected_result_cpp = ["","","","","" "#ifdef SOMETHING int do_somethingelse(){return v ; } #else int dont_do_nothing(){return 0 ; } #endif" ] # yapf: enable def test_preproc(): ''' ignores_new lines ''' parser = Parser() parse_batch_run( _in, expected_result_hpp, expected_result_cpp, lambda i, pos, h: parser._parse_preprocessor_stuff(i, pos, h)) def test_preproc_parser(): ''' uses main parse function parse_block which determines what is contained in each line ''' parser = Parser() parse_batch_run(_in, expected_result_hpp, expected_result_cpp, lambda i, pos, h: parser.parse_block(i, pos, h))
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_preprocessor.py", "copies": "1", "size": "1687", "license": "mit", "hash": 4274007295528230000, "line_mean": 28.0862068966, "line_max": 141, "alpha_frac": 0.5749851808, "autogenerated": false, "ratio": 3.367265469061876, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44422506498618763, "avg_score": null, "num_lines": null }
from functionrefactor.parser import Parser from tests.common_functions import * def test_namespace(): ''' ignores_new lines ''' _in = [ "namespace Nutella", "{", "}", "namespace PeanutButter{", "}", "namespace Cereal{ //something", "}" ] expected_result_hpp = [ "namespace Nutella {}// namespace Nutella", "namespace PeanutButter {}// namespace PeanutButter", "namespace Cereal {//something}// namespace Cereal" ] expected_result_cpp = [ "namespace Nutella {}// namespace Nutella", "namespace PeanutButter {}// namespace PeanutButter", "namespace Cereal {}// namespace Cereal" ] parser = Parser() parse_batch_run(_in, expected_result_hpp, expected_result_cpp, lambda i, txt, h: parser._parse_namespace_block(i, txt, h)) def test_class(): ''' ignores_new lines ''' _in = [ "class Nutella", "{", "};", "class PeanutButter{", "};", "class PeanutButter{//something", "};" ] expected_result_hpp = [ "class Nutella {}; ", "class PeanutButter {}; ", "class PeanutButter {//something}; " ] expected_result_cpp = ["", "", ""] parser = Parser() parse_batch_run(_in, expected_result_hpp, expected_result_cpp, lambda i, txt, h: parser._parse_class_block(i, txt, h))
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_namespace_class.py", "copies": "1", "size": "1367", "license": "mit", "hash": 4967958465855710000, "line_mean": 30.0681818182, "line_max": 79, "alpha_frac": 0.5749817118, "autogenerated": false, "ratio": 3.4089775561097255, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9483959267909725, "avg_score": 0, "num_lines": 44 }
from functionrefactor.parser import Parser, Regex, FunctionVariableParser from tests.common_functions import * def test_variable_capture(): rg = Regex() parser = FunctionVariableParser(rg) [keywords, name, rhs] = parser._extract_variable_components('int i;') is_equal(''.join([f.format_hpp() for f in keywords]), 'int') is_equal(name, 'i') is_equal(rhs, ';') [keywords, name, rhs] = parser._extract_variable_components( 'const auto& index = 0;') is_equal(''.join([f.format_hpp() for f in keywords]), 'const auto&') is_equal(name, 'index') is_equal(rhs, '=0;') [keywords, name, rhs] = parser._extract_variable_components( 'const auto& index {0};') is_equal(''.join([f.format_hpp() for f in keywords]), 'const auto&') is_equal(name, 'index') is_equal(rhs, '{0};') [keywords, name, rhs] = parser._extract_variable_components( r'const std::ForwardIterator<int>* begin{*ptr};') is_equal(''.join([f.format_hpp() for f in keywords]), r'const std::ForwardIterator<int> *') is_equal(name, 'begin') is_equal(rhs, '{*ptr};') def test_variables(): ''' ignores_new lines ''' _in = [ "int i;", "int i = 0;", "int i{0};", "auto i = (0);", "std::vector<int> vec {1,2,3,4};", "std::vector<float> vec\n", "= { 0.f , 2.f , 4.f , 8.f };" ] expected_result_hpp = [ "int i;", "int i= 0;", "int i{0};", "auto i= (0);", "std::vector<int> vec{1,2,3,4};", "std::vector<float> vec= { 0.f , 2.f , 4.f , 8.f };" ] expected_result_cpp = ["", "", "", "", "", ""] rg = Regex() parser = FunctionVariableParser(rg) parse_batch_run(_in, expected_result_hpp, expected_result_cpp, lambda i, pos, h: parser.parse(i, pos, h)) def test_functions(): ''' ignores_new lines ''' _in = [ 'void func();', 'std::string get_key(int index_pos = 0);', 'std::string get_key(int index_pos = 0)', '{return ptr->find_key(index_pos);\n', '}', 'std::vector<int> get_vector(int min_number = 0, int max_number = 10);' ] expected_result_hpp = [ 'void func();', 'std::string get_key(int index_pos= 0);', 'std::string get_key(int index_pos= 0);', 'std::vector<int> get_vector(int min_number = 0, int max_number = 10);' ] expected_result_cpp = [ 'void func() {}', 'std::string get_key(int index_pos) {}', 'std::string get_key(int index_pos){return ptr->find_key(index_pos);}', 'std::vector<int> get_vector(int min_number, int max_number) {}' ] rg = Regex() parser = FunctionVariableParser(rg) parse_batch_run(_in, expected_result_hpp, expected_result_cpp, lambda i, pos, h: parser.parse(i, pos, h)) _class = ClassDef("class", "Base") _in = ["void do_things(){ do_other_things();}", ""] it = enumerate(_in) pos = next(it)[1] _parser = Parser() try: _parser.parse_block(it, pos, _class) except StopIteration: pass is_equal( _class.format_cpp(None), "void Base::do_things(){ do_other_things();}")
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_var_function.py", "copies": "1", "size": "3169", "license": "mit", "hash": -8142715969349956000, "line_mean": 32.3578947368, "line_max": 79, "alpha_frac": 0.5531713474, "autogenerated": false, "ratio": 3.1438492063492065, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4197020553749206, "avg_score": null, "num_lines": null }
from functionrefactor.parser import Parser, TemplateParser, Regex from tests.common_functions import * def test_templates(): ''' ignores_new lines ''' _in = [ "template <typename T>", "template <class Name = std::ForwardIterator>", "template", "<typename TT, typename U, int X_size = 10>", "template", "<typename T=float,", "typename C=long long>", "" ] expected_result_hpp = [ "using T = change_this;", "using Name = std::ForwardIterator;", "using TT = change_this;\nusing U = change_this;\nconstexpr int X_size = 10;", "using T = float;\nusing C = long long;" ] expected_result_cpp = ["", "", "", ""] rg = Regex() parser = TemplateParser(rg) parse_batch_run(_in, expected_result_hpp, expected_result_cpp, lambda i, pos, h: parser.parse(i, pos, h)) def test_template_parser(): ''' uses main parse function parse_block which determines what is contained in each line ''' _in = [ "template <typename T>", "template <class Name = std::ForwardIterator>", "template", "<typename TT, typename U, int X_size = 10>", "template", "<typename T=float,", "typename C=long long>", "" ] expected_result_hpp = [ "\nusing T = change_this;\n", "using Name = std::ForwardIterator;\n", "using TT = change_this;\nusing U = change_this;\nconstexpr int X_size = 10;\n", "using T = float;\nusing C = long long;\n" ] expected_result_cpp = ["", "", "", "", "", "", ""] parser = Parser() h = HeaderDef() it = enumerate(_in) pos = next(it)[1] try: parser.parse_block(it, pos, h) except StopIteration: pass is_equal(h.format_hpp(), ''.join(expected_result_hpp)) is_equal(h.format_cpp(), "")
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_template_args.py", "copies": "1", "size": "1798", "license": "mit", "hash": 7369688482586793000, "line_mean": 33.5769230769, "line_max": 96, "alpha_frac": 0.5795328142, "autogenerated": false, "ratio": 3.5393700787401574, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4618902892940157, "avg_score": null, "num_lines": null }
from functionrefactor.parser import Regex from tests.common_functions import * def test_comment_regex(): r = Regex() assert r.comment_single_line.match("//comment") assert r.comment_single_line.match(" //comment something") assert r.comment_multiline.match(" /*comment something*/") assert r.comment_multiline.match(" /*comment \n something*/") assert r.comment_multiline_begin.match( " /*comment \n something \n \n \n \n") assert r.comment_multiline_begin.match(" /*c++") assert r.comment_multiline_end.match("comment */") assert r.comment_multiline_end.match("comment \n something \n */ ") def test_preprocessor_regex(): r = Regex() assert r.preprocessor_c.match("#define") assert r.preprocessor_c.match("#define MACRO_ SOMETHING(){} \ ") assert r.includes.match("#include <string>") assert r.includes.match("#include \"_header\" ") assert r.generic_preprocessor.match("#ifdef SOMETHING") assert r.generic_preprocessor.match("#endif //SOMETHING ELSE") assert r.line_continuation.match(r"#define MACRO \ ") assert r.line_continuation.match(r"return CAPSLOCKMANDATORY; \ ") def test_class_namespace_regex(): r = Regex() assert r.namespace.match("namespace std \n {") assert r.namespace.match(" namespace SuperNamespace{") assert r.class_.match("class Nutella{") assert not r.class_.match(" class;") assert r.class_.match("class Porridge{") assert r.struct_.match("struct{") assert r.struct_.match(" struct \n \n Cereal{") assert r.union_.match(' union Oats{ }') assert r.union_.match(' union Variant{ ') def test_template_arg_packing(): r = Regex() assert r.template.match(' template typename<>') # look for template start assert r.template.match(' template') # look for template start assert r.template_args.search("template <typename T>") assert r.template_args.search( "template <class T0, class T1, \n int X = 10 >") assert r.template_args.search( "template <class T0, class T1, \n int X = 10 > /* */") def test_text_quotes(): r = Regex() assert r.string_block.search(r" \" something ))) \" ") assert r.char_block.search(r" \' c \' ") def test_variable_and_function_regex(): r = Regex() assert r.is_variable.match("int var;") assert r.is_variable.match("auto i{0};") assert r.is_variable.match("int i =0;") assert r.is_variable.match("auto i{0};") assert r.is_variable.match("std::vector<std::string> vec{};") assert r.is_variable.match( r"std::vector<std::string> vec={\"a\",\"b\",\"c\"}; //abc") assert r.is_variable.match( r"std::vector<std::string> vec=(\"a\",\"b\",\"c\"); //abc") assert r.is_variable.match(r"std::vector<std::string> vec=(\n); //abc") assert r.is_variable.match("std::vector<std::string> vec\n{\n}\n;") assert r.is_variable.match( "constexpr f = [&](auto& a, auto& b)->{return a+b;}") assert r.is_variable.match( "constexpr f = [&](auto& a, auto& b)->{\n return a+b; \n}") assert not r.is_variable.match("int main();") assert not r.is_variable.match("int main() { }") assert not r.is_variable.match( "virtual std::string get_tag(const std::string& key)=0; ") # assert r.is_variable.match(r"int i(0); //abc") note this is not a valid variable declaration # in a C++ header file, so no test for this is needed full_regex_match("auto i =0;", r.variable_capture) full_regex_match("auto i{0};", r.variable_capture) full_regex_match("std::vector<std::string> vec{};", r.variable_capture) full_regex_match(r"std::vector<std::string> vec={\"a\",\"b\",\"c\"};", r.variable_capture) full_regex_match(r"std::vector<std::string> vec=(\"a\",\"b\",\"c\");", r.variable_capture) full_regex_match(r"std::vector<std::string> vec=(\n);", r.variable_capture) full_regex_match("std::vector<std::string> vec\n{\n}\n;", r.variable_capture) #lambda test full_regex_match("constexpr f = [&](auto& a, auto& b)->{return a+b;};", r.variable_capture) full_regex_match( "constexpr f = [&](auto& a, auto& b)->{\n return a+b; \n};", r.variable_capture) #function match assert r.is_function.match(" int main();") assert r.is_function.match("int main() { }") assert r.is_function.match("void do_things(const i* const ptr) {}") assert r.is_function.match( " virtual std::string get_tag(const std::string& key)=0; ") assert not r.is_function.match("auto i =0;") assert not r.is_function.match("auto i{0};") assert not r.is_function.match("std::vector<std::string> vec{};") assert not r.is_function.match( r"std::vector<std::string> vec={\"a\",\"b\",\"c\"}; //abc") assert not r.is_function.match( r"std::vector<std::string> vec=(\"a\",\"b\",\"c\"); //abc") assert not r.is_function.match(r"std::vector<std::string> vec=(\n); //abc") assert not r.is_function.match("std::vector<std::string> vec\n{\n}\n;") full_regex_match("int main();", r.function_capture) full_regex_match("int main(){}", r.function_capture) full_regex_match("long long get_key(){\n return 42; \n}", r.function_capture) full_regex_match("long long get_key(int k){\n return k+42; \n}", r.function_capture) full_regex_match("long long \n get_key() \n {\n return 42; \n}", r.function_capture) #function parameters extraction assert r.function_parameters.search( "int main(const std::string& a, const std::vector<int>& vec);") assert r.function_parameters.search("int main();") assert r.function_parameters.search( "int main(const std::string& a, const std::vector<int>& vec = { 1, 2, 3, 4} );" ) #verification that the full parameter list is extracted in all cases full_regex_search( "int main(const std::string& a, const std::vector<int>& vec);", r.function_parameters, "(const std::string& a, const std::vector<int>& vec)") full_regex_search( "int main(const std::string& a, const std::vector<int>& vec = {1,2,3,4});", r.function_parameters, "(const std::string& a, const std::vector<int>& vec = {1,2,3,4})") full_regex_search( "int main(const std::string& a, \n const std::vector<int>& vec \n = {1,2,3,4});", r.function_parameters, "(const std::string& a, \n const std::vector<int>& vec \n = {1,2,3,4})")
{ "repo_name": "astrodroid/functionrefactor", "path": "tests/test_regex.py", "copies": "1", "size": "6642", "license": "mit", "hash": -514456622692939200, "line_mean": 41.8516129032, "line_max": 99, "alpha_frac": 0.6052393857, "autogenerated": false, "ratio": 3.224271844660194, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9321644663961681, "avg_score": 0.0015733132797026961, "num_lines": 155 }
from functionrefactor.settings import settings from functionrefactor.string_utilities import append, append_list, is_invalid, first_word from abc import ABC, abstractmethod import re __all__ = [ 'Abstract', 'Comments', 'TemplateArgs', 'TemplateArg', 'Keywords', 'Variable', 'FunctionDef' ] class Abstract(ABC): """abstract base class ensures and interface consistency """ def __init__(self): super(AbstractOperation, self).__init__() @abstractmethod def format_cpp(self, parent, override_andshow=False): pass @abstractmethod def format_hpp(self, parent): pass @abstractmethod def add_component(self, component): pass @abstractmethod def get_name(self): return None @abstractmethod def get_type(self): return None ''' defaults to false: Note that if a parent is not visible the children might be visible still for example a class declaration and definition is expected in the header but the implemntation of the functions is in the source file, if the parent class needs to override the default normal behaviour then the format_cpp has that option that is only used in the comment class so far ''' def is_visible_in_cpp(self): return False class Comments(Abstract): """comment string goes here""" def __init__(self, _comments): self.comments = _comments.strip() self.set_multiline_comment = False def __format(self): # return a empty string in cases the comments are null to avoid # creating too many new lines if self.comments.isspace(): return "" if self.set_multiline_comment: self.comments.replace("//", "") return "/* " + self.comments + " */\n" else: return self.comments + "\n" def format_cpp(self, parent, override_andshow=False): if override_andshow: return self.__format() else: return "\n" def format_hpp(self, *_): return self.__format() def add_component(self, component): pass def get_name(self): return None def get_type(self): return 'Comments' def is_visible_in_cpp(self): return False class TemplateArgs(Abstract): def __init__(self): self.args = [] def add_component(self, arg): self.args.append(arg) def _all_arguments_tobeconverted(self): for t in self.args: if not t.is_active: return False return True def _format_template(self): return_val = "template\n<" for i, t in enumerate(self.args): if (not t.is_active): return_val = append(return_val, t._type, " ", t._name) if i < len(self.args) - 1: return_val = append(return_val, ", ") return_val = append(return_val, ">\n") return return_val def format_hpp(self, *_): return_val = ''.join( [t.format_hpp() for t in self.args if t.is_active]) if not self._all_arguments_tobeconverted(): return_val = append(self._format_template(), return_val) return return_val def format_cpp(self, *_): return "" def get_name(self): return None def get_type(self): return 'TemplateArgs' class TemplateArg(Abstract): """definition of a template argument name is the alias of thetype type is whatever is a an typename/class or some kind of constant like int (for example) templates are replaced by a using statement, and constants (within a template) are replaced with a constexpr constant If a default value is given for the template parameter, then that is used """ def __init__(self, _type, _name, default_value=None): self.name = _name self.type = _type self.is_active = True if default_value == None or default_value == "": self.default_value = "change_this" else: self.default_value = default_value def deactivate_conversion(self): '''deactivates the conversion of this template argument, will be outouted as template <typename self.name>''' self.is_active = False def set_argument_replacement(self, replace_with_this): """replaces reference to this tempate argument with the following variable, if not set it will be replaced with a using statement where the end user will need to specify the correct type """ self.replacement = replace_with_this def format_hpp(self, *_): if not self.is_active: return "" if self.type == "class" or self.type == "typename": return "using " + self.name + " = " + self.default_value + ";\n" else: return "constexpr " + self.type + " " + self.name + " = " + self.default_value + ";\n" def format_cpp(self, *_): return "" def add_component(self, component): pass def get_name(self): return None def get_type(self): return 'TemplateArg' class Keywords(Abstract): """definition of keywords included, examples of keywords include const, inline, override, virtual, noexcept, a config file determines which of these keywords are to be placed in the cpp file as well and which are not""" def __init__(self, value): self.keyword_value = value def format_hpp(self): return self.keyword_value + " " def format_cpp(self, *_): if self.is_visible_in_cpp: return self.keyword_value + " " else: return "" def add_component(self, component): pass def get_name(self): return self.keyword_value def get_type(self): return 'Keywords' def is_visible_in_cpp(self): return settings.use_keyword_in_cpp(self.keyword_value) class Variable(Abstract): """definition of a single argument type in a class key_words: const or anything else that might apply here name: this is what you call that variable is_function_argument: prevents adding ";" for function arguments variables rhs is the rhs of the variable equal excluded """ def __init__(self, key_words, name, is_function_argument, rhs): self.name = name self.key_words = key_words if is_invalid(rhs): self.rhs = None else: self.rhs = rhs self.is_function_argument = is_function_argument self.is_active = True def deactivate_conversion(self): self.is_active = False def _format(self, parent): #classdef type is garanteed to have a name if parent != None and parent.get_type() == 'ClassDef': return ''.join([x.format_hpp() for x in self.key_words ]) + parent.get_name() + "::" + self.name else: return ''.join( [x.format_hpp() for x in self.key_words]) + self.name def format_hpp(self, *_): if is_invalid(self.name): return '' return_val = self._format(None) if self.rhs: return_val = append(return_val, self.rhs) return return_val def format_cpp(self, parent, *_): #static variables need to initialised in the cpp file if self.is_visible_in_cpp(parent): return self._format(parent) + self.rhs if self.is_function_argument: return self._format(None) return "" def add_component(self, component): pass def get_name(self): return self.name def get_type(self): return 'Variable' def is_visible_in_cpp(self, *_): return "static" in [x.format_hpp() for x in self.key_words] class FunctionDef(Abstract): """definition of a function/void pre_keywords: is what is on the left of the function name including returning type etc etc etc name: is what you call the function function_args: all the inputs Variable List """ def __init__(self, pre_keywords, name, function_args, post_keywords, func_body): self.pre_keywords = pre_keywords self.name = name self.function_args = function_args self.post_keywords = post_keywords self.function_body = func_body self.is_active = True self.initialiser_list_re = re.compile(r'[\"\'\.\(\)\,a-zA-Z0-9\s]*\{') def deactivate_conversion(self): self.is_active = False def _format_function_declaration(self, parent): ''' formats a function excluding it's implementation handles the case where the parent is a class type adding the ParentName:: before the function name ''' # returntype const etc.. return_val = ''.join([x.format_cpp() for x in self.pre_keywords]) if parent != None and parent.get_type() == 'ClassDef': return_val = append( return_val, " " + parent.get_name() + "::" + self.name + "(") else: return_val = append(return_val, self.name + "(") if parent: return_val = append_list( return_val, [k.format_cpp(parent) for k in self.function_args], ', ') + ')' else: return_val = append_list( return_val, [k.format_hpp(parent) for k in self.function_args], ', ') + ')' # any further keywords such as const noexcept etc... return append_list(return_val, [k.format_cpp() for k in self.post_keywords]) def _format_function_implementation(self, parent): if is_invalid(self.function_body): return "\n {\n" + "\n}\n" elif len(self.pre_keywords) == 0 and self.initialiser_list_re.match( self.function_body): #constructor with an initialiser list return ':' + self.function_body else: return "{\n" + self.function_body def format_cpp(self, parent, *_): """format_cpp: formats a file to export in a cpp file""" if not self.is_visible_in_cpp(): return '' return self._format_function_declaration( parent) + self._format_function_implementation(parent) def format_hpp(self, *_): if not self.is_visible_in_cpp(): return self._format_function_declaration( None) + self._format_function_implementation(None) # returntype const etc.. return self._format_function_declaration(None) + ';' def add_component(self, component): pass def get_name(self): return self.name def get_type(self): return 'FunctionDef' def is_visible_in_cpp(self): ''' looks for keys which imply the function is not to be moved over, for example inline''' for keya in self.pre_keywords: if settings.dont_move_oncpp_ifpresent(keya.get_name()): return False for keyb in self.post_keywords: if settings.dont_move_oncpp_ifpresent(keyb.get_name()): return False return True
{ "repo_name": "astrodroid/functionrefactor", "path": "functionrefactor/header_components.py", "copies": "1", "size": "11268", "license": "mit", "hash": -2037451159844147000, "line_mean": 29.956043956, "line_max": 121, "alpha_frac": 0.5907880724, "autogenerated": false, "ratio": 4.085569253081943, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5176357325481943, "avg_score": null, "num_lines": null }
from functionrefactor.string_utilities import * from functionrefactor.header_components import * __all__ = ['PreprocessorStuff', 'ClassDef', 'NamespaceDef', 'HeaderDef'] class PreprocessorStuff(Abstract): """Preprocessor things like #includes, #ifdef and MACROS""" def __init__(self, text): self.text = text self.nested_declarations = [] def format_cpp(self, parent, override_andshow): key = first_word(self.text).strip() #main thing this if statement does is to check for variables that are to be moved in the cpp file #OR an override from the parent class # the first #ifdef, #if is the parent class and subequent statements are all child of the same parent if self.is_visible_in_cpp(): return self.text + " " + ''.join([ d.format_cpp(parent, True) + '\n' for d in self.nested_declarations ]) + "\n#endif" elif override_andshow: return self.text + " " + ''.join([ d.format_cpp(parent, True) + '\n' for d in self.nested_declarations ]) elif key in [ '#define', '#include', 'public:', 'private:', 'protected:' ]: return '' else: return ''.join([ d.format_cpp(parent, False) + '\n' for d in self.nested_declarations ]) def format_hpp(self, parent): key = first_word(self.text).strip() if key in ['#if', '#ifndef', '#ifdef']: return self.text + '\n' + ''.join([ d.format_hpp(parent) + '\n' for d in self.nested_declarations ]) + "\n#endif" else: return self.text + '\n' + ''.join([ d.format_hpp(parent) + '\n' for d in self.nested_declarations ]) def add_component(self, component): self.nested_declarations.append(component) return self.nested_declarations[-1] def get_name(self): return None def get_type(self): return 'PreprocessorStuff' def is_visible_in_cpp(self): return 'FunctionDef' in [ d.get_type() for d in self.nested_declarations if d.is_visible_in_cpp() ] class ClassDef(Abstract): """ type: class or struct or even union as this script doesn't care what it is private_declarations is all variab """ def __init__(self, _type, name): self.type = _type self.name = name self.components = [] def deactivate_conversion(self): self.is_active = False def add_component(self, d): ''' expects an already constructed object that implements: format_cpp and format_hpp methods returns last element ''' self.components.append(d) return d def _format_begin(self): return self.type + " " + self.name + " {\n" def _format_end(self): return "}; \n" def format_cpp(self, parent, *_): show_it = True return_val = "\n" for i in range(len(self.components)): _elem = self.components[i] if i < len(self.components) - 1: _next = self._get_next(i) #ensure comment linked to something visible is also shown show_it = _next.is_visible_in_cpp() and _elem.get_type( ) == 'Comments' or _elem.is_visible_in_cpp() else: show_it = _elem.is_visible_in_cpp() if show_it: return_val = append(return_val, _elem.format_cpp(self, True),'\n') return return_val + '\n' def format_hpp(self, parent): return_val = self._format_begin() for d in self.components: return_val = append(return_val, d.format_hpp(self)) return_val = append(return_val, self._format_end(),'\n') return return_val def get_name(self): return self.name def get_type(self): return 'ClassDef' def is_visible_in_cpp(self): return 'FunctionDef' in [ d.get_type() for d in self.components if d.is_visible_in_cpp() ] def _get_next(self, start_index): return next(d for index, d in enumerate(self.components) if index > start_index) class NamespaceDef(Abstract): """ defines a namespace name: is the name of the namespace` nested_declarations: all declarations that are within the namespace block, other namespaces, classes functions, namespace scope variables etc... """ def __init__(self, name): self.name = name self.nested_declarations = [] def add_component(self, declaration): self.nested_declarations.append(declaration) return declaration def is_visible_in_cpp(self, *_): return True def _format_begin(self): return "namespace " + self.name + " {\n" def _format_end(self): return "}// namespace " + self.name + "\n" def format_cpp(self, parent, *_): return_val = self._format_begin() for d in self.nested_declarations: return_val = append(return_val, d.format_cpp(self, False)) return_val = append(return_val, self._format_end()) return return_val def format_hpp(self, parent): return_val = self._format_begin() for d in self.nested_declarations: return_val = append(return_val, d.format_hpp(self)) return_val = append(return_val, self._format_end()) return return_val def get_name(self): return self.name def get_type(self): return 'NamespaceDef' class HeaderDef(Abstract): """ contains all the header declarations tree including namespace, functions etc the decision of what is to be included in the cpp or hpp file is up to the nested_declarations objects """ def __init__(self): self.nested_declarations = [] def add_component(self, declaration): self.nested_declarations.append(declaration) return declaration def clear(self): self.nested_declarations = [] def is_visible_in_cpp(self, *_): return False def format_cpp(self, header_name=None): return_val = "\n" if header_name: return_val = "#import \"" + header_name + "\"\n" for d in self.nested_declarations: return_val = append(return_val, d.format_cpp(self, False)) return return_val def get_lines_cpp(self, header_file=None): '''returns the program output (source cpp file) splitted into lines''' return self.format_cpp(header_file).split('\n') def format_hpp(self): return_val = "\n" for d in self.nested_declarations: return_val = append(return_val, d.format_hpp(self)) return return_val def get_lines_hpp(self): '''returns the program output (header file) splitted into lines''' return self.format_hpp().split('\n') def get_name(self): return None def get_type(self): return 'HeaderDef'
{ "repo_name": "astrodroid/functionrefactor", "path": "functionrefactor/header.py", "copies": "1", "size": "7150", "license": "mit", "hash": -3039453959271494700, "line_mean": 29.4255319149, "line_max": 148, "alpha_frac": 0.5745454545, "autogenerated": false, "ratio": 3.9502762430939224, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005539472458792607, "num_lines": 235 }
from functions2 import rm_duplicate_arrays import numpy as np class Map(object): def __init__(self, map=None): self.map = map def invert(self): inverted_map = np.zeros(self.map.size) for x in range(self.map.size): inverted_map[self.map[x]] = x self.map = inverted_map def proliferate(self, proliferation_functions): new_maps = [self.map] for function in proliferation_functions: new_maps += function(self.map) new_maps = rm_duplicate_arrays(new_maps) return new_maps def freq_key(self, ciphertext, natural_sample): if np.all(ciphertext.rates[0] == None): ciphertext.group_frequencies(1) if np.all(natural_sample.rates[0] == None): natural_sample.group_frequencies(1) ciphertext_ranking = np.argsort(ciphertext.rates[0]) natural_ranking = np.argsort(natural_sample.rates[0]) self.map = np.zeros(len(ciphertext.rates[0]), dtype=np.int32) for i, x in enumerate(ciphertext_ranking): self.map[x] = natural_ranking[i]
{ "repo_name": "paulsbrookes/subcipher", "path": "map.py", "copies": "2", "size": "1104", "license": "apache-2.0", "hash": 5664270165529510000, "line_mean": 35.8, "line_max": 69, "alpha_frac": 0.6222826087, "autogenerated": false, "ratio": 3.54983922829582, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.517212183699582, "avg_score": null, "num_lines": null }
from functions.FE import FE from fitness import Classifier from sklearn.preprocessing import MinMaxScaler import numpy as np import pandas as pd import ga def testIris(): iris = pd.read_csv("data/iris.data", sep=",") irisAtts = iris.drop("class", 1) target = iris["class"] #Scale to [0,1] before expanding scaledIris = MinMaxScaler().fit_transform(irisAtts) bestSingleMatch = {'knn': [(1,5) for x in range(4)], 'cart': [(3,2) for x in range(4)], 'svm': [(7,4) for x in range(4)]} functionalExp = FE() for cl in ['knn', 'cart', 'svm']: model = Classifier(cl, target, folds=10, jobs=6) print("original accuracy " + cl + " " + str(model.getAccuracy(irisAtts))) expandedData = functionalExp.expandMatrix(scaledIris, bestSingleMatch[cl]) print("single match expansion accuracy " + cl + " " + str(model.getAccuracy(expandedData))) gafe = ga.GAFE(model, scaledIris, target, scaled=True) avg, bestPair = gafe.runGAFE(n_population=21, n_iter=1, verbose=True) print("gafe " + cl + " " + str(avg) ) def main(): testIris() if __name__ == "__main__": main()
{ "repo_name": "andreabduque/GAFE", "path": "main.py", "copies": "1", "size": "1148", "license": "mit", "hash": 5517076589336832000, "line_mean": 33.7878787879, "line_max": 125, "alpha_frac": 0.6324041812, "autogenerated": false, "ratio": 3.188888888888889, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43212930700888885, "avg_score": null, "num_lines": null }
from FunctionsforCOL import calculate_score from flask import Flask, request, render_template app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def komplikator(): if request.method == 'POST': gender = request.form['gender'] age = request.form['age'] status = request.form['status'] ignorance = request.form['ignorance'] money_have = request.form['money_have'] money_wants = request.form['money_wants'] money_spent = request.form['money_spent'] online_popularity = request.form['online_popularity'] rl_friends = request.form['rl_friends'] if age.isdigit() and money_have.isdigit() and money_spent.isdigit() and money_wants.isdigit() and online_popularity.isdigit() and rl_friends.isdigit(): return render_template('komplikator_result.html', complexity = calculate_score(gender, age, status, ignorance, money_have, money_wants, money_spent, online_popularity, rl_friends)) else: return render_template('komplikator_error.html', message = "Age, Ignorance, Money have, Money wants, Money spent and Klout score must be digits without special signs!") else: return render_template('komplikator_form.html') if __name__ == "__main__": app.run(debug = True)
{ "repo_name": "CodeCatz/litterbox", "path": "Natasa/ComplexLifeCalc/server.py", "copies": "1", "size": "1297", "license": "mit", "hash": 5784510773784876000, "line_mean": 47.0740740741, "line_max": 192, "alpha_frac": 0.66692367, "autogenerated": false, "ratio": 3.6128133704735377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47797370404735373, "avg_score": null, "num_lines": null }
from .function.signature import NoDefault from transmute_core.http_parameters import ParamSet, Param from .exceptions import APIException, NoSerializerFound NoArgument = object() class ParamExtractor(object): """ An abstract object to extend to handle extracting parameters from a request. """ NoArgument = NoArgument def extract_params(self, context, transmute_func, content_type): parameters = transmute_func.parameters signature = transmute_func.signature content_type = content_type or context.contenttype_serializers.default.main_type args = {} framework_args = self._get_framework_args() for key, value in framework_args.items(): if signature.get_argument(key): args[key] = value empty_args = [] for name, param in parameters.query.items(): arginfo = param.arginfo if name in framework_args: continue schema = context.serializers.to_json_schema(arginfo.type) is_list = "items" in schema values = self._query_argument(name, is_list) if values is NoArgument: empty_args.append(arginfo) else: if is_list and len(values) == 1: values = values[0].split(",") args[name] = context.serializers.load(arginfo.type, values) for name, param in parameters.header.items(): arginfo = param.arginfo if name in framework_args: continue value = self._header_argument(name) if value is NoArgument: empty_args.append(arginfo) else: args[name] = context.serializers.load(arginfo.type, value) if isinstance(parameters.body, Param) or len(parameters.body) > 0: try: serializer = context.contenttype_serializers[content_type] except NoSerializerFound: raise APIException( "unable to extract parameters for content type {0}. Supported types are: {1}".format( content_type, context.contenttype_serializers.keys() ) ) if not self.body: body_dict = {} else: body_dict = serializer.load(self.body) if isinstance(parameters.body, Param): arginfo = parameters.body.arginfo args[arginfo.name] = context.serializers.load(arginfo.type, body_dict) else: for name, param in parameters.body.items(): arginfo = param.arginfo if name in framework_args: continue if name in body_dict: args[name] = context.serializers.load( arginfo.type, body_dict[name] ) else: empty_args.append(arginfo) for name, param in parameters.path.items(): arginfo = param.arginfo if name in framework_args: continue values = self._path_argument(name) if values is not NoArgument: args[name] = context.serializers.load(arginfo.type, values) else: empty_args.append(arginfo) required_params_not_passed = [] for arg in empty_args: if arg.default is NoDefault: required_params_not_passed.append(arg.name) else: args[arg.name] = arg.default if len(required_params_not_passed) > 0: raise APIException( "required arguments {0} not passed".format(required_params_not_passed) ) return signature.split_args(args) def _get_framework_args(self): """ often, a framework provides specific variables that are passed into the handler function (e.g. the request object in aiohttp). return a dictionary of these arguments, which will be added to the function arguments if they appear. """ pass @property def body(self): """ return the request body. """ raise NotImplementedError() def _query_argument(self, key, is_list): raise NotImplementedError() def _header_argument(self, key): raise NotImplementedError() def _path_argument(self, key): raise NotImplementedError() def _fold(param_or_param_set, value_dict, request_context): # a single parameter consumes the whole dict if isinstance(param_or_param_set, Param): arginfo = param_or_param_set.arginfo value = request_context.context.serializers.load(arginfo.type, value_dict) request_context.args[argument.name] = value # a param set consumes the dict piece by piece else: for name, param in param_or_param_set.values(): arginfo = param.arginfo if name in request_context.framework_args: continue if name in value_dict: value = context.serializers.load(arginfo.type, value_dict[name]) request_context.args[arginfo.name] = value elif arginfo.default is not NoDefault: request_context.args[arginfo.name] = arginfo.default else: request_context.empty_args.append(name)
{ "repo_name": "toumorokoshi/web-transmute", "path": "transmute_core/param_extractor.py", "copies": "2", "size": "5495", "license": "mit", "hash": -4548414594602940000, "line_mean": 35.8791946309, "line_max": 105, "alpha_frac": 0.5716105551, "autogenerated": false, "ratio": 4.602177554438861, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00045672681107977964, "num_lines": 149 }
from ...functions import adjoint, conjugate from .matexpr import MatrixExpr class Transpose(MatrixExpr): """ The transpose of a matrix expression. This is a symbolic object that simply stores its argument without evaluating it. To actually compute the transpose, use the ``transpose()`` function, or the ``.T`` attribute of matrices. Examples ======== >>> A = MatrixSymbol('A', 3, 5) >>> B = MatrixSymbol('B', 5, 3) >>> Transpose(A) A.T >>> A.T == transpose(A) == Transpose(A) True >>> Transpose(A*B) (A*B).T >>> transpose(A*B) B.T*A.T """ is_Transpose = True def doit(self, **hints): arg = self.arg if hints.get('deep', True): arg = arg.doit(**hints) result = arg._eval_transpose() return result if result is not None else Transpose(arg) @property def arg(self): return self.args[0] @property def shape(self): return self.arg.shape[::-1] def _entry(self, i, j): return self.arg._entry(j, i) def _eval_adjoint(self): return conjugate(self.arg) def _eval_conjugate(self): return adjoint(self.arg) def _eval_transpose(self): return self.arg def _eval_trace(self): from .trace import Trace return Trace(self.arg) # Trace(X.T) => Trace(X) def _eval_determinant(self): from .determinant import det return det(self.arg) def transpose(expr): """Matrix transpose.""" return Transpose(expr).doit()
{ "repo_name": "diofant/diofant", "path": "diofant/matrices/expressions/transpose.py", "copies": "2", "size": "1560", "license": "bsd-3-clause", "hash": 7447227735293431000, "line_mean": 21.6086956522, "line_max": 77, "alpha_frac": 0.583974359, "autogenerated": false, "ratio": 3.705463182897862, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5289437541897862, "avg_score": null, "num_lines": null }
from .functions import BaseAnalysisFunction import wave import subprocess import textgrid import os import tempfile def is_autovot_friendly_file(sound_file): rate = subprocess.run(["soxi", "-r", sound_file], encoding="UTF-8", stdout=subprocess.PIPE).stdout if int(rate) != 16000: return False channels = subprocess.run(["soxi", "-c", sound_file], encoding="UTF-8", stdout=subprocess.PIPE).stdout if int(channels) != 1: return False return True def resample_for_autovot(soundfile, tmpdir): output_file = os.path.join(tmpdir, "sound_file.wav") subprocess.call(["sox", soundfile, "-c", "1", "-r", "16000", output_file]) return output_file class MeasureVOTPretrained(object): def __init__(self, classifier_to_use=None, min_vot_length=15, max_vot_length=250, window_max=30, window_min=30, debug=False): if classifier_to_use is None: raise ValueError("There must be a classifier to run AutoVOT") else: self.classifier_to_use = classifier_to_use self.min_vot_length = min_vot_length self.max_vot_length = max_vot_length self.debug = debug self.window_max = window_max self.window_min = window_min def __call__(self, segment): file_path = os.path.expanduser(segment["file_path"]) begin = segment["begin"] end = segment["end"] vot_marks = sorted(segment["vot_marks"], key=lambda x: x[0]) grid = textgrid.TextGrid(maxTime=end) vot_tier = textgrid.IntervalTier(name='vot', maxTime=end) for vot_begin, vot_end, *extra_data in vot_marks: vot_tier.add(vot_begin, vot_end, 'vot') grid.append(vot_tier) with tempfile.TemporaryDirectory() as tmpdirname: grid_path = "{}/file.TextGrid".format(tmpdirname) csv_path = "{}/file.csv".format(tmpdirname) wav_filenames = "{}/wavs.txt".format(tmpdirname) textgrid_filenames = "{}/textgrids.txt".format(tmpdirname) if not is_autovot_friendly_file(file_path): file_path = resample_for_autovot(file_path, tmpdirname) with open(wav_filenames, 'w') as f: f.write("{}\n".format(file_path)) with open(textgrid_filenames, 'w') as f: f.write("{}\n".format(grid_path)) grid.write(grid_path) if self.debug: grid.write('/tmp/textgrid_from_conch.csv') with open('/tmp/alt_wordlist.txt', 'w') as f: f.write("{}\n".format('/tmp/textgrid_from_conch.csv')) subprocess.run(["auto_vot_decode.py", wav_filenames, '/tmp/alt_wordlist.txt', self.classifier_to_use, '--vot_tier', 'vot', '--vot_mark', 'vot', "--min_vot_length", str(self.min_vot_length), "--max_vot_length", str(self.max_vot_length), "--window_max", str(self.window_max), "--window_min", str(self.window_min)]) subprocess.run(["auto_vot_decode.py", wav_filenames, textgrid_filenames, self.classifier_to_use, '--vot_tier', 'vot', '--vot_mark', 'vot', '--csv_file', csv_path, "--min_vot_length", str(self.min_vot_length), "--max_vot_length", str(self.max_vot_length), "--window_max", str(self.window_max), "--window_min", str(self.window_min)]) return_list = [] with open(csv_path, "r") as f: f.readline() for l, (b, e, *extra_data) in zip(f, vot_marks): _, time, vot, confidence = l.split(',') if "neg 0\n" == confidence: confidence = 0 return_list.append((float(time), float(vot), float(confidence), *extra_data)) return return_list class AutoVOTAnalysisFunction(BaseAnalysisFunction): def __init__(self, classifier_to_use=None, min_vot_length=15, max_vot_length=250, window_max=30, window_min=30, debug=False, arguments=None): super(AutoVOTAnalysisFunction, self).__init__() self._function = MeasureVOTPretrained(classifier_to_use=classifier_to_use, min_vot_length=min_vot_length, max_vot_length=max_vot_length, window_max=window_max, window_min=window_min, debug=debug) self.requires_file = True self.uses_segments = True self.requires_segment_as_arg = True
{ "repo_name": "mmcauliffe/python-acoustic-similarity", "path": "conch/analysis/autovot.py", "copies": "1", "size": "4312", "license": "mit", "hash": -178741565068646, "line_mean": 48.5632183908, "line_max": 343, "alpha_frac": 0.6069109462, "autogenerated": false, "ratio": 3.3323029366306027, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9411052647639859, "avg_score": 0.005632247038148577, "num_lines": 87 }
from functions import check_hadoop_services, check_local_path from .exceptions import CustomRequestFailed from rest_framework import permissions actions= ['start', 'stop', 'restart', 'upload', 'run', 'check'] class HadoopPermission(permissions.BasePermission): """ Validity check for hadoop actions. """ def has_permission(self, request, view): # Check validity of action parameter action = request.GET.get('action') if action is None: raise CustomRequestFailed('No action parameter provided.') if action not in actions: keys = ",".join(actions["actions"].keys()) message = "The provided action " + action + ", is not in the list of accepted actions: [" + keys + "]." raise CustomRequestFailed(message) running = check_hadoop_services() if action == "start" and running: raise CustomRequestFailed("All of the hadoop services are running.") elif (action != "stop" and action != "start" and action != "check") and not running: raise CustomRequestFailed("Not all of the hadoop services are running.Start them and try again.") # Check validity of request parameters per request method method = request.META['REQUEST_METHOD'] if method == 'POST': if action == 'upload': path = request.data.get("path") dest = request.data.get("dest") if path is None or dest is None: raise CustomRequestFailed("No path or dest values provided.") check_local_path(path) elif action == 'run': path = request.data.get("path") args = request.data.get("args") if path is None or args is None: raise CustomRequestFailed("No path or args values provided.") check_local_path(path) return True
{ "repo_name": "efikalti/Lambda", "path": "backend/app/permissions.py", "copies": "1", "size": "1936", "license": "apache-2.0", "hash": -2031137135038328000, "line_mean": 44.023255814, "line_max": 115, "alpha_frac": 0.6022727273, "autogenerated": false, "ratio": 4.733496332518337, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5835769059818336, "avg_score": null, "num_lines": null }
from functions import continuedFraction import math def fraction(pList): '''from the list pList = [a0 a1 a2 ...] returns the corresponding fraction P/Q ''' length = len(pList) p,q = 1,0 lP, lQ = [pList[0]], [1] p1 = pList[1] * lP[0] + p q1 = pList[1] * lQ[0] + q lP.append(p1) lQ.append(q1) for i in range(2,length): # print lP,lQ pi = pList[i]* lP[i-1] + lP[i-2] qi = pList[i]* lQ[i-1] + lQ[i-2] lP.append(pi) lQ.append(qi) return [lP,lQ] def pellSolution(pNumber): '''return the solution of Pell equation x*x - pNumber*y*y = 1''' l = continuedFraction(pNumber, pNumber*2) # print l t = fraction(l) P,Q = t[0], t[1] for i in range(len(P)): pi,qi = P[i], Q[i] # print pi,qi if pi*pi- pNumber*qi*qi == 1: return [pi,qi] def test() : l = [1,2,3,4] # print fraction(l) A = [2,3,5,6,7,61] for a in A: print pellSolution(a) test() def main() : maximum = -1 limit = 1000 for a in range(2,limit+1): t = int(math.sqrt(a)) if a!= t*t: p= pellSolution(a) x = p[0] if x > maximum: maximum = x print a,p main()
{ "repo_name": "nguyenkims/projecteuler-python", "path": "src/p66.py", "copies": "1", "size": "1082", "license": "mit", "hash": -120811543194817260, "line_mean": 18.6909090909, "line_max": 65, "alpha_frac": 0.5804066543, "autogenerated": false, "ratio": 2.0847784200385355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.31651850743385357, "avg_score": null, "num_lines": null }
from functions import defun, defun_wrapped, defun_static @defun def stieltjes(ctx, n, a=1): n = ctx.convert(n) a = ctx.convert(a) if n < 0: return ctx.bad_domain("Stieltjes constants defined for n >= 0") if hasattr(ctx, "stieltjes_cache"): stieltjes_cache = ctx.stieltjes_cache else: stieltjes_cache = ctx.stieltjes_cache = {} if a == 1: if n == 0: return +ctx.euler if n in stieltjes_cache: prec, s = stieltjes_cache[n] if prec >= ctx.prec: return +s mag = 1 def f(x): xa = x/a v = (xa-ctx.j)*ctx.ln(a-ctx.j*x)**n/(1+xa**2)/(ctx.exp(2*ctx.pi*x)-1) return ctx._re(v) / mag orig = ctx.prec try: # Normalize integrand by approx. magnitude to # speed up quadrature (which uses absolute error) if n > 50: ctx.prec = 20 mag = ctx.quad(f, [0,ctx.inf], maxdegree=3) ctx.prec = orig + 10 + int(n**0.5) s = ctx.quad(f, [0,ctx.inf], maxdegree=20) v = ctx.ln(a)**n/(2*a) - ctx.ln(a)**(n+1)/(n+1) + 2*s/a*mag finally: ctx.prec = orig if a == 1 and ctx.isint(n): stieltjes_cache[n] = (ctx.prec, v) return +v @defun_wrapped def siegeltheta(ctx, t): if ctx._im(t): # XXX: cancellation occurs a = ctx.loggamma(0.25+0.5j*t) b = ctx.loggamma(0.25-0.5j*t) return -ctx.ln(ctx.pi)/2*t - 0.5j*(a-b) else: if ctx.isinf(t): return t return ctx._im(ctx.loggamma(0.25+0.5j*t)) - ctx.ln(ctx.pi)/2*t @defun_wrapped def grampoint(ctx, n): # asymptotic expansion, from # http://mathworld.wolfram.com/GramPoint.html g = 2*ctx.pi*ctx.exp(1+ctx.lambertw((8*n+1)/(8*ctx.e))) return ctx.findroot(lambda t: ctx.siegeltheta(t)-ctx.pi*n, g) @defun_wrapped def siegelz(ctx, t): v = ctx.expj(ctx.siegeltheta(t))*ctx.zeta(0.5+ctx.j*t) if ctx._is_real_type(t): return ctx._re(v) return v _zeta_zeros = [ 14.134725142,21.022039639,25.010857580,30.424876126,32.935061588, 37.586178159,40.918719012,43.327073281,48.005150881,49.773832478, 52.970321478,56.446247697,59.347044003,60.831778525,65.112544048, 67.079810529,69.546401711,72.067157674,75.704690699,77.144840069, 79.337375020,82.910380854,84.735492981,87.425274613,88.809111208, 92.491899271,94.651344041,95.870634228,98.831194218,101.317851006, 103.725538040,105.446623052,107.168611184,111.029535543,111.874659177, 114.320220915,116.226680321,118.790782866,121.370125002,122.946829294, 124.256818554,127.516683880,129.578704200,131.087688531,133.497737203, 134.756509753,138.116042055,139.736208952,141.123707404,143.111845808, 146.000982487,147.422765343,150.053520421,150.925257612,153.024693811, 156.112909294,157.597591818,158.849988171,161.188964138,163.030709687, 165.537069188,167.184439978,169.094515416,169.911976479,173.411536520, 174.754191523,176.441434298,178.377407776,179.916484020,182.207078484, 184.874467848,185.598783678,187.228922584,189.416158656,192.026656361, 193.079726604,195.265396680,196.876481841,198.015309676,201.264751944, 202.493594514,204.189671803,205.394697202,207.906258888,209.576509717, 211.690862595,213.347919360,214.547044783,216.169538508,219.067596349, 220.714918839,221.430705555,224.007000255,224.983324670,227.421444280, 229.337413306,231.250188700,231.987235253,233.693404179,236.524229666, ] def _load_zeta_zeros(url): import urllib d = urllib.urlopen(url) L = [float(x) for x in d.readlines()] # Sanity check assert round(L[0]) == 14 _zeta_zeros[:] = L @defun def oldzetazero(ctx, n, url='http://www.dtc.umn.edu/~odlyzko/zeta_tables/zeros1'): n = int(n) if n < 0: return ctx.zetazero(-n).conjugate() if n == 0: raise ValueError("n must be nonzero") if n > len(_zeta_zeros) and n <= 100000: _load_zeta_zeros(url) if n > len(_zeta_zeros): raise NotImplementedError("n too large for zetazeros") return ctx.mpc(0.5, ctx.findroot(ctx.siegelz, _zeta_zeros[n-1])) @defun_wrapped def riemannr(ctx, x): if x == 0: return ctx.zero # Check if a simple asymptotic estimate is accurate enough if abs(x) > 1000: a = ctx.li(x) b = 0.5*ctx.li(ctx.sqrt(x)) if abs(b) < abs(a)*ctx.eps: return a if abs(x) < 0.01: # XXX ctx.prec += int(-ctx.log(abs(x),2)) # Sum Gram's series s = t = ctx.one u = ctx.ln(x) k = 1 while abs(t) > abs(s)*ctx.eps: t = t * u / k s += t / (k * ctx._zeta_int(k+1)) k += 1 return s @defun_static def primepi(ctx, x): x = int(x) if x < 2: return 0 return len(ctx.list_primes(x)) # TODO: fix the interface wrt contexts @defun_wrapped def primepi2(ctx, x): x = int(x) if x < 2: return ctx._iv.zero if x < 2657: return ctx._iv.mpf(ctx.primepi(x)) mid = ctx.li(x) # Schoenfeld's estimate for x >= 2657, assuming RH err = ctx.sqrt(x,rounding='u')*ctx.ln(x,rounding='u')/8/ctx.pi(rounding='d') a = ctx.floor((ctx._iv.mpf(mid)-err).a, rounding='d') b = ctx.ceil((ctx._iv.mpf(mid)+err).b, rounding='u') return ctx._iv.mpf([a,b]) @defun_wrapped def primezeta(ctx, s): if ctx.isnan(s): return s if ctx.re(s) <= 0: raise ValueError("prime zeta function defined only for re(s) > 0") if s == 1: return ctx.inf if s == 0.5: return ctx.mpc(ctx.ninf, ctx.pi) r = ctx.re(s) if r > ctx.prec: return 0.5**s else: wp = ctx.prec + int(r) def terms(): orig = ctx.prec # zeta ~ 1+eps; need to set precision # to get logarithm accurately k = 0 while 1: k += 1 u = ctx.moebius(k) if not u: continue ctx.prec = wp t = u*ctx.ln(ctx.zeta(k*s))/k if not t: return #print ctx.prec, ctx.nstr(t) ctx.prec = orig yield t return ctx.sum_accurately(terms) # TODO: for bernpoly and eulerpoly, ensure that all exact zeros are covered @defun_wrapped def bernpoly(ctx, n, z): # Slow implementation: #return sum(ctx.binomial(n,k)*ctx.bernoulli(k)*z**(n-k) for k in xrange(0,n+1)) n = int(n) if n < 0: raise ValueError("Bernoulli polynomials only defined for n >= 0") if z == 0 or (z == 1 and n > 1): return ctx.bernoulli(n) if z == 0.5: return (ctx.ldexp(1,1-n)-1)*ctx.bernoulli(n) if n <= 3: if n == 0: return z ** 0 if n == 1: return z - 0.5 if n == 2: return (6*z*(z-1)+1)/6 if n == 3: return z*(z*(z-1.5)+0.5) if ctx.isinf(z): return z ** n if ctx.isnan(z): return z if abs(z) > 2: def terms(): t = ctx.one yield t r = ctx.one/z k = 1 while k <= n: t = t*(n+1-k)/k*r if not (k > 2 and k & 1): yield t*ctx.bernoulli(k) k += 1 return ctx.sum_accurately(terms) * z**n else: def terms(): yield ctx.bernoulli(n) t = ctx.one k = 1 while k <= n: t = t*(n+1-k)/k * z m = n-k if not (m > 2 and m & 1): yield t*ctx.bernoulli(m) k += 1 return ctx.sum_accurately(terms) @defun_wrapped def eulerpoly(ctx, n, z): n = int(n) if n < 0: raise ValueError("Euler polynomials only defined for n >= 0") if n <= 2: if n == 0: return z ** 0 if n == 1: return z - 0.5 if n == 2: return z*(z-1) if ctx.isinf(z): return z**n if ctx.isnan(z): return z m = n+1 if z == 0: return -2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 if z == 1: return 2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 if z == 0.5: if n % 2: return ctx.zero # Use exact code for Euler numbers if n < 100 or n*ctx.mag(0.46839865*n) < ctx.prec*0.25: return ctx.ldexp(ctx._eulernum(n), -n) # http://functions.wolfram.com/Polynomials/EulerE2/06/01/02/01/0002/ def terms(): t = ctx.one k = 0 w = ctx.ldexp(1,n+2) while 1: v = n-k+1 if not (v > 2 and v & 1): yield (2-w)*ctx.bernoulli(v)*t k += 1 if k > n: break t = t*z*(n-k+2)/k w *= 0.5 return ctx.sum_accurately(terms) / m @defun def eulernum(ctx, n, exact=False): n = int(n) if exact: return int(ctx._eulernum(n)) if n < 100: return ctx.mpf(ctx._eulernum(n)) if n % 2: return ctx.zero return ctx.ldexp(ctx.eulerpoly(n,0.5), n) # TODO: this should be implemented low-level def polylog_series(ctx, s, z): tol = +ctx.eps l = ctx.zero k = 1 zk = z while 1: term = zk / k**s l += term if abs(term) < tol: break zk *= z k += 1 return l def polylog_continuation(ctx, n, z): if n < 0: return z*0 twopij = 2j * ctx.pi a = -twopij**n/ctx.fac(n) * ctx.bernpoly(n, ctx.ln(z)/twopij) if ctx._is_real_type(z) and z < 0: a = ctx._re(a) if ctx._im(z) < 0 or (ctx._im(z) == 0 and ctx._re(z) >= 1): a -= twopij*ctx.ln(z)**(n-1)/ctx.fac(n-1) return a def polylog_unitcircle(ctx, n, z): tol = +ctx.eps if n > 1: l = ctx.zero logz = ctx.ln(z) logmz = ctx.one m = 0 while 1: if (n-m) != 1: term = ctx.zeta(n-m) * logmz / ctx.fac(m) if term and abs(term) < tol: break l += term logmz *= logz m += 1 l += ctx.ln(z)**(n-1)/ctx.fac(n-1)*(ctx.harmonic(n-1)-ctx.ln(-ctx.ln(z))) elif n < 1: # else l = ctx.fac(-n)*(-ctx.ln(z))**(n-1) logz = ctx.ln(z) logkz = ctx.one k = 0 while 1: b = ctx.bernoulli(k-n+1) if b: term = b*logkz/(ctx.fac(k)*(k-n+1)) if abs(term) < tol: break l -= term logkz *= logz k += 1 else: raise ValueError if ctx._is_real_type(z) and z < 0: l = ctx._re(l) return l def polylog_general(ctx, s, z): v = ctx.zero u = ctx.ln(z) if not abs(u) < 5: # theoretically |u| < 2*pi raise NotImplementedError("polylog for arbitrary s and z") t = 1 k = 0 while 1: term = ctx.zeta(s-k) * t if abs(term) < ctx.eps: break v += term k += 1 t *= u t /= k return ctx.gamma(1-s)*(-u)**(s-1) + v @defun_wrapped def polylog(ctx, s, z): s = ctx.convert(s) z = ctx.convert(z) if z == 1: return ctx.zeta(s) if z == -1: return -ctx.altzeta(s) if s == 0: return z/(1-z) if s == 1: return -ctx.ln(1-z) if s == -1: return z/(1-z)**2 if abs(z) <= 0.75 or (not ctx.isint(s) and abs(z) < 0.9): return polylog_series(ctx, s, z) if abs(z) >= 1.4 and ctx.isint(s): return (-1)**(s+1)*polylog_series(ctx, s, 1/z) + polylog_continuation(ctx, s, z) if ctx.isint(s): return polylog_unitcircle(ctx, int(s), z) return polylog_general(ctx, s, z) #raise NotImplementedError("polylog for arbitrary s and z") # This could perhaps be used in some cases #from quadrature import quad #return quad(lambda t: t**(s-1)/(exp(t)/z-1),[0,inf])/gamma(s) @defun_wrapped def clsin(ctx, s, z, pi=False): if ctx.isint(s) and s < 0 and int(s) % 2 == 1: return z*0 if pi: a = ctx.expjpi(z) else: a = ctx.expj(z) if ctx._is_real_type(z) and ctx._is_real_type(s): return ctx.im(ctx.polylog(s,a)) b = 1/a return (-0.5j)*(ctx.polylog(s,a) - ctx.polylog(s,b)) @defun_wrapped def clcos(ctx, s, z, pi=False): if ctx.isint(s) and s < 0 and int(s) % 2 == 0: return z*0 if pi: a = ctx.expjpi(z) else: a = ctx.expj(z) if ctx._is_real_type(z) and ctx._is_real_type(s): return ctx.re(ctx.polylog(s,a)) b = 1/a return 0.5*(ctx.polylog(s,a) + ctx.polylog(s,b)) @defun def altzeta(ctx, s, **kwargs): try: return ctx._altzeta(s, **kwargs) except NotImplementedError: return ctx._altzeta_generic(s) @defun_wrapped def _altzeta_generic(ctx, s): if s == 1: return ctx.ln2 + 0*s return -ctx.powm1(2, 1-s) * ctx.zeta(s) @defun def zeta(ctx, s, a=1, derivative=0, method=None, **kwargs): d = int(derivative) if a == 1 and not (d or method): try: return ctx._zeta(s, **kwargs) except NotImplementedError: pass s = ctx.convert(s) prec = ctx.prec method = kwargs.get('method') verbose = kwargs.get('verbose') if a == 1 and method != 'euler-maclaurin': im = abs(ctx._im(s)) re = abs(ctx._re(s)) #if (im < prec or method == 'borwein') and not derivative: # try: # if verbose: # print "zeta: Attempting to use the Borwein algorithm" # return ctx._zeta(s, **kwargs) # except NotImplementedError: # if verbose: # print "zeta: Could not use the Borwein algorithm" # pass if abs(im) > 500*prec and 10*re < prec and derivative <= 4 or \ method == 'riemann-siegel': try: # py2.4 compatible try block try: if verbose: print "zeta: Attempting to use the Riemann-Siegel algorithm" return ctx.rs_zeta(s, derivative, **kwargs) except NotImplementedError: if verbose: print "zeta: Could not use the Riemann-Siegel algorithm" pass finally: ctx.prec = prec if s == 1: return ctx.inf abss = abs(s) if abss == ctx.inf: if ctx.re(s) == ctx.inf: if d == 0: return ctx.one return ctx.zero return s*0 elif ctx.isnan(abss): return 1/s if ctx.re(s) > 2*ctx.prec and a == 1 and not derivative: return ctx.one + ctx.power(2, -s) if verbose: print "zeta: Using the Euler-Maclaurin algorithm" prec = ctx.prec try: ctx.prec += 10 v = ctx._hurwitz(s, a, d) finally: ctx.prec = prec return +v @defun def _hurwitz(ctx, s, a=1, d=0): # We strongly want to special-case rational a a, atype = ctx._convert_param(a) prec = ctx.prec # TODO: implement reflection for derivatives res = ctx.re(s) negs = -s try: if res < 0 and not d: # Integer reflection formula if ctx.isnpint(s): n = int(res) if n <= 0: return ctx.bernpoly(1-n, a) / (n-1) t = 1-s # We now require a to be standardized v = 0 shift = 0 b = a while ctx.re(b) > 1: b -= 1 v -= b**negs shift -= 1 while ctx.re(b) <= 0: v += b**negs b += 1 shift += 1 # Rational reflection formula if atype == 'Q' or atype == 'Z': try: p, q = a._mpq_ except: assert a == int(a) p = int(a) q = 1 p += shift*q assert 1 <= p <= q g = ctx.fsum(ctx.cospi(t/2-2*k*b)*ctx._hurwitz(t,(k,q)) \ for k in range(1,q+1)) g *= 2*ctx.gamma(t)/(2*ctx.pi*q)**t v += g return v # General reflection formula else: C1, C2 = ctx.cospi_sinpi(0.5*t) # Clausen functions; could maybe use polylog directly if C1: C1 *= ctx.clcos(t, 2*a, pi=True) if C2: C2 *= ctx.clsin(t, 2*a, pi=True) v += 2*ctx.gamma(t)/(2*ctx.pi)**t*(C1+C2) return v except NotImplementedError: pass a = ctx.convert(a) tol = -prec # Estimate number of terms for Euler-Maclaurin summation; could be improved M1 = 0 M2 = prec // 3 N = M2 lsum = 0 # This speeds up the recurrence for derivatives if ctx.isint(s): s = int(ctx._re(s)) s1 = s-1 while 1: # Truncated L-series l = ctx._zetasum(s, M1+a, M2-M1-1, [d])[0][0] #if d: # l = ctx.fsum((-ctx.ln(n+a))**d * (n+a)**negs for n in range(M1,M2)) #else: # l = ctx.fsum((n+a)**negs for n in range(M1,M2)) lsum += l M2a = M2+a logM2a = ctx.ln(M2a) logM2ad = logM2a**d logs = [logM2ad] logr = 1/logM2a rM2a = 1/M2a M2as = rM2a**s if d: tailsum = ctx.gammainc(d+1, s1*logM2a) / s1**(d+1) else: tailsum = 1/((s1)*(M2a)**s1) tailsum += 0.5 * logM2ad * M2as U = [1] r = M2as fact = 2 for j in range(1, N+1): # TODO: the following could perhaps be tidied a bit j2 = 2*j if j == 1: upds = [1] else: upds = [j2-2, j2-1] for m in upds: D = min(m,d+1) if m <= d: logs.append(logs[-1] * logr) Un = [0]*(D+1) for i in xrange(D): Un[i] = (1-m-s)*U[i] for i in xrange(1,D+1): Un[i] += (d-(i-1))*U[i-1] U = Un r *= rM2a t = ctx.fdot(U, logs) * r * ctx.bernoulli(j2)/(-fact) tailsum += t if ctx.mag(t) < tol: return lsum + (-1)**d * tailsum fact *= (j2+1)*(j2+2) M1, M2 = M2, M2*2 @defun def _zetasum(ctx, s, a, n, derivatives=[0], reflect=False): """ Returns [xd0,xd1,...,xdr], [yd0,yd1,...ydr] where xdk = D^k ( 1/a^s + 1/(a+1)^s + ... + 1/(a+n)^s ) ydk = D^k conj( 1/a^(1-s) + 1/(a+1)^(1-s) + ... + 1/(a+n)^(1-s) ) D^k = kth derivative with respect to s, k ranges over the given list of derivatives (which should consist of either a single element or a range 0,1,...r). If reflect=False, the ydks are not computed. """ #print "zetasum", s, a, n try: return ctx._zetasum_fast(s, a, n, derivatives, reflect) except NotImplementedError: pass negs = ctx.fneg(s, exact=True) have_derivatives = derivatives != [0] have_one_derivative = len(derivatives) == 1 if not reflect: if not have_derivatives: return [ctx.fsum((a+k)**negs for k in xrange(n+1))], [] if have_one_derivative: d = derivatives[0] x = ctx.fsum(ctx.ln(a+k)**d * (a+k)**negs for k in xrange(n+1)) return [(-1)**d * x], [] maxd = max(derivatives) if not have_one_derivative: derivatives = range(maxd+1) xs = [ctx.zero for d in derivatives] if reflect: ys = [ctx.zero for d in derivatives] else: ys = [] for k in xrange(n+1): w = a + k xterm = w ** negs if reflect: yterm = ctx.conj(ctx.one / (w * xterm)) if have_derivatives: logw = -ctx.ln(w) if have_one_derivative: logw = logw ** maxd xs[0] += xterm * logw if reflect: ys[0] += yterm * logw else: t = ctx.one for d in derivatives: xs[d] += xterm * t if reflect: ys[d] += yterm * t t *= logw else: xs[0] += xterm if reflect: ys[0] += yterm return xs, ys @defun def dirichlet(ctx, s, chi=[1], derivative=0): s = ctx.convert(s) q = len(chi) d = int(derivative) if d > 2: raise NotImplementedError("arbitrary order derivatives") prec = ctx.prec try: ctx.prec += 10 if s == 1: have_pole = True for x in chi: if x and x != 1: have_pole = False h = +ctx.eps ctx.prec *= 2*(d+1) s += h if have_pole: return +ctx.inf z = ctx.zero for p in range(1,q+1): if chi[p%q]: if d == 1: z += chi[p%q] * (ctx.zeta(s, (p,q), 1) - \ ctx.zeta(s, (p,q))*ctx.log(q)) else: z += chi[p%q] * ctx.zeta(s, (p,q)) z /= q**s finally: ctx.prec = prec return +z
{ "repo_name": "mattpap/sympy-polys", "path": "sympy/mpmath/functions/zeta.py", "copies": "3", "size": "21328", "license": "bsd-3-clause", "hash": 3918138467259775000, "line_mean": 29.7319884726, "line_max": 88, "alpha_frac": 0.4938109527, "autogenerated": false, "ratio": 2.9184455391351944, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9871876157557871, "avg_score": 0.008076066855464541, "num_lines": 694 }
from functions import defun, defun_wrapped def _check_need_perturb(ctx, terms, prec, discard_known_zeros): perturb = recompute = False extraprec = 0 discard = [] for term_index, term in enumerate(terms): w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term have_singular_nongamma_weight = False # Avoid division by zero in leading factors (TODO: # also check for near division by zero?) for k, w in enumerate(w_s): if not w: if ctx.re(c_s[k]) <= 0 and c_s[k]: perturb = recompute = True have_singular_nongamma_weight = True pole_count = [0, 0, 0] # Check for gamma and series poles and near-poles for data_index, data in enumerate([alpha_s, beta_s, b_s]): for i, x in enumerate(data): n, d = ctx.nint_distance(x) # Poles if n > 0: continue if d == ctx.ninf: # OK if we have a polynomial # ------------------------------ ok = False if data_index == 2: for u in a_s: if ctx.isnpint(u) and u >= int(n): ok = True break if ok: continue pole_count[data_index] += 1 # ------------------------------ #perturb = recompute = True #return perturb, recompute, extraprec elif d < -4: extraprec += -d recompute = True if discard_known_zeros and pole_count[1] > pole_count[0] + pole_count[2] \ and not have_singular_nongamma_weight: discard.append(term_index) elif sum(pole_count): perturb = recompute = True return perturb, recompute, extraprec, discard _hypercomb_msg = """ hypercomb() failed to converge to the requested %i bits of accuracy using a working precision of %i bits. The function value may be zero or infinite; try passing zeroprec=N or infprec=M to bound finite values between 2^(-N) and 2^M. Otherwise try a higher maxprec or maxterms. """ @defun def hypercomb(ctx, function, params=[], discard_known_zeros=True, **kwargs): orig = ctx.prec sumvalue = ctx.zero dist = ctx.nint_distance ninf = ctx.ninf orig_params = params[:] verbose = kwargs.get('verbose', False) maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(orig)) kwargs['maxprec'] = maxprec # For calls to hypsum zeroprec = kwargs.get('zeroprec') infprec = kwargs.get('infprec') perturbed_reference_value = None hextra = 0 try: while 1: ctx.prec += 10 if ctx.prec > maxprec: raise ValueError(_hypercomb_msg % (orig, ctx.prec)) orig2 = ctx.prec params = orig_params[:] terms = function(*params) if verbose: print print "ENTERING hypercomb main loop" print "prec =", ctx.prec print "hextra", hextra perturb, recompute, extraprec, discard = \ _check_need_perturb(ctx, terms, orig, discard_known_zeros) ctx.prec += extraprec if perturb: if "hmag" in kwargs: hmag = kwargs["hmag"] elif ctx._fixed_precision: hmag = int(ctx.prec*0.3) else: hmag = orig + 10 + hextra h = ctx.ldexp(ctx.one, -hmag) ctx.prec = orig2 + 10 + hmag + 10 for k in range(len(params)): params[k] += h # Heuristically ensure that the perturbations # are "independent" so that two perturbations # don't accidentally cancel each other out # in a subtraction. h += h/(k+1) if recompute: terms = function(*params) if discard_known_zeros: terms = [term for (i, term) in enumerate(terms) if i not in discard] if not terms: return ctx.zero evaluated_terms = [] for term_index, term_data in enumerate(terms): w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term_data if verbose: print print " Evaluating term %i/%i : %iF%i" % \ (term_index+1, len(terms), len(a_s), len(b_s)) print " powers", ctx.nstr(w_s), ctx.nstr(c_s) print " gamma", ctx.nstr(alpha_s), ctx.nstr(beta_s) print " hyper", ctx.nstr(a_s), ctx.nstr(b_s) print " z", ctx.nstr(z) v = ctx.hyper(a_s, b_s, z, **kwargs) for a in alpha_s: v *= ctx.gamma(a) for b in beta_s: v /= ctx.gamma(b) for w, c in zip(w_s, c_s): v *= ctx.power(w, c) if verbose: print " Value:", v evaluated_terms.append(v) if len(terms) == 1 and (not perturb): sumvalue = evaluated_terms[0] break if ctx._fixed_precision: sumvalue = ctx.fsum(evaluated_terms) break sumvalue = ctx.fsum(evaluated_terms) term_magnitudes = [ctx.mag(x) for x in evaluated_terms] max_magnitude = max(term_magnitudes) sum_magnitude = ctx.mag(sumvalue) cancellation = max_magnitude - sum_magnitude if verbose: print print " Cancellation:", cancellation, "bits" print " Increased precision:", ctx.prec - orig, "bits" precision_ok = cancellation < ctx.prec - orig if zeroprec is None: zero_ok = False else: zero_ok = max_magnitude - ctx.prec < -zeroprec if infprec is None: inf_ok = False else: inf_ok = max_magnitude > infprec if precision_ok and (not perturb) or ctx.isnan(cancellation): break elif precision_ok: if perturbed_reference_value is None: hextra += 20 perturbed_reference_value = sumvalue continue elif ctx.mag(sumvalue - perturbed_reference_value) <= \ ctx.mag(sumvalue) - orig: break elif zero_ok: sumvalue = ctx.zero break elif inf_ok: sumvalue = ctx.inf break elif 'hmag' in kwargs: break else: hextra *= 2 perturbed_reference_value = sumvalue # Increase precision else: increment = min(max(cancellation, orig//2), max(extraprec,orig)) ctx.prec += increment if verbose: print " Must start over with increased precision" continue finally: ctx.prec = orig return +sumvalue @defun def hyper(ctx, a_s, b_s, z, **kwargs): """ Hypergeometric function, general case. """ z = ctx.convert(z) p = len(a_s) q = len(b_s) a_s = map(ctx._convert_param, a_s) b_s = map(ctx._convert_param, b_s) # Reduce degree by eliminating common parameters if kwargs.get('eliminate', True): i = 0 while i < q and a_s: b = b_s[i] if b in a_s: a_s.remove(b) b_s.remove(b) p -= 1 q -= 1 else: i += 1 # Handle special cases if p == 0: if q == 1: return ctx._hyp0f1(b_s, z, **kwargs) elif q == 0: return ctx.exp(z) elif p == 1: if q == 1: return ctx._hyp1f1(a_s, b_s, z, **kwargs) elif q == 2: return ctx._hyp1f2(a_s, b_s, z, **kwargs) elif q == 0: return ctx._hyp1f0(a_s[0][0], z) elif p == 2: if q == 1: return ctx._hyp2f1(a_s, b_s, z, **kwargs) elif q == 2: return ctx._hyp2f2(a_s, b_s, z, **kwargs) elif q == 3: return ctx._hyp2f3(a_s, b_s, z, **kwargs) elif q == 0: return ctx._hyp2f0(a_s, b_s, z, **kwargs) elif p == q+1: return ctx._hypq1fq(p, q, a_s, b_s, z, **kwargs) elif p > q+1 and not kwargs.get('force_series'): return ctx._hyp_borel(p, q, a_s, b_s, z, **kwargs) coeffs, types = zip(*(a_s+b_s)) return ctx.hypsum(p, q, types, coeffs, z, **kwargs) @defun def hyp0f1(ctx,b,z,**kwargs): return ctx.hyper([],[b],z,**kwargs) @defun def hyp1f1(ctx,a,b,z,**kwargs): return ctx.hyper([a],[b],z,**kwargs) @defun def hyp1f2(ctx,a1,b1,b2,z,**kwargs): return ctx.hyper([a1],[b1,b2],z,**kwargs) @defun def hyp2f1(ctx,a,b,c,z,**kwargs): return ctx.hyper([a,b],[c],z,**kwargs) @defun def hyp2f2(ctx,a1,a2,b1,b2,z,**kwargs): return ctx.hyper([a1,a2],[b1,b2],z,**kwargs) @defun def hyp2f3(ctx,a1,a2,b1,b2,b3,z,**kwargs): return ctx.hyper([a1,a2],[b1,b2,b3],z,**kwargs) @defun def hyp2f0(ctx,a,b,z,**kwargs): return ctx.hyper([a,b],[],z,**kwargs) @defun def hyp3f2(ctx,a1,a2,a3,b1,b2,z,**kwargs): return ctx.hyper([a1,a2,a3],[b1,b2],z,**kwargs) @defun_wrapped def _hyp1f0(ctx, a, z): return (1-z) ** (-a) @defun def _hyp0f1(ctx, b_s, z, **kwargs): (b, btype), = b_s if z: magz = ctx.mag(z) else: magz = 0 if magz >= 8 and not kwargs.get('force_series'): try: # http://functions.wolfram.com/HypergeometricFunctions/ # Hypergeometric0F1/06/02/03/0004/ # We don't need hypercomb because the only possible singularity # occurs when the value is undefined. However, we should perhaps # still check for cancellation... # TODO: handle the all-real case more efficiently! # TODO: figure out how much precision is needed (exponential growth) orig = ctx.prec try: ctx.prec += 12 + magz//2 w = ctx.sqrt(-z) jw = ctx.j*w u = 1/(4*jw) c = ctx.mpq_1_2 - b E = ctx.exp(2*jw) H1 = (-jw)**c/E*ctx.hyp2f0(b-ctx.mpq_1_2, ctx.mpq_3_2-b, -u, force_series=True) H2 = (jw)**c*E*ctx.hyp2f0(b-ctx.mpq_1_2, ctx.mpq_3_2-b, u, force_series=True) v = ctx.gamma(b)/(2*ctx.sqrt(ctx.pi))*(H1 + H2) finally: ctx.prec = orig if ctx._is_real_type(b) and ctx._is_real_type(z): v = ctx._re(v) return +v except ctx.NoConvergence: pass return ctx.hypsum(0, 1, (btype,), [b], z, **kwargs) @defun def _hyp1f1(ctx, a_s, b_s, z, **kwargs): (a, atype), = a_s (b, btype), = b_s if not z: return ctx.one+z magz = ctx.mag(z) if magz >= 7 and not (ctx.isint(a) and ctx.re(a) <= 0): if ctx.isinf(z): if ctx.sign(a) == ctx.sign(b) == ctx.sign(z) == 1: return ctx.inf return ctx.nan * z try: try: ctx.prec += magz sector = ctx._im(z) < 0 and ctx._re(z) <= 0 def h(a,b): if sector: E = ctx.expjpi(ctx.fneg(a, exact=True)) else: E = ctx.expjpi(a) rz = 1/z T1 = ([E,z], [1,-a], [b], [b-a], [a, 1+a-b], [], -rz) T2 = ([ctx.exp(z),z], [1,a-b], [b], [a], [b-a, 1-a], [], rz) return T1, T2 v = ctx.hypercomb(h, [a,b], force_series=True) if ctx._is_real_type(a) and ctx._is_real_type(b) and ctx._is_real_type(z): v = ctx._re(v) return +v except ctx.NoConvergence: pass finally: ctx.prec -= magz v = ctx.hypsum(1, 1, (atype, btype), [a, b], z, **kwargs) return v def _hyp2f1_gosper(ctx,a,b,c,z,**kwargs): # Use Gosper's recurrence # See http://www.math.utexas.edu/pipermail/maxima/2006/000126.html _a,_b,_c,_z = a, b, c, z orig = ctx.prec maxprec = kwargs.get('maxprec', 100*orig) extra = 10 while 1: ctx.prec = orig + extra #a = ctx.convert(_a) #b = ctx.convert(_b) #c = ctx.convert(_c) z = ctx.convert(_z) d = ctx.mpf(0) e = ctx.mpf(1) f = ctx.mpf(0) k = 0 # Common subexpression elimination, unfortunately making # things a bit unreadable. The formula is quite messy to begin # with, though... abz = a*b*z ch = c * ctx.mpq_1_2 c1h = (c+1) * ctx.mpq_1_2 nz = 1-z g = z/nz abg = a*b*g cba = c-b-a z2 = z-2 tol = -ctx.prec - 10 nstr = ctx.nstr nprint = ctx.nprint mag = ctx.mag maxmag = ctx.ninf while 1: kch = k+ch kakbz = (k+a)*(k+b)*z / (4*(k+1)*kch*(k+c1h)) d1 = kakbz*(e-(k+cba)*d*g) e1 = kakbz*(d*abg+(k+c)*e) ft = d*(k*(cba*z+k*z2-c)-abz)/(2*kch*nz) f1 = f + e - ft maxmag = max(maxmag, mag(f1)) if mag(f1-f) < tol: break d, e, f = d1, e1, f1 k += 1 cancellation = maxmag - mag(f1) if cancellation < extra: break else: extra += cancellation if extra > maxprec: raise ctx.NoConvergence return f1 @defun def _hyp2f1(ctx, a_s, b_s, z, **kwargs): (a, atype), (b, btype) = a_s (c, ctype), = b_s if z == 1: # TODO: the following logic can be simplified convergent = ctx.re(c-a-b) > 0 finite = (ctx.isint(a) and a <= 0) or (ctx.isint(b) and b <= 0) zerodiv = ctx.isint(c) and c <= 0 and not \ ((ctx.isint(a) and c <= a <= 0) or (ctx.isint(b) and c <= b <= 0)) #print "bz", a, b, c, z, convergent, finite, zerodiv # Gauss's theorem gives the value if convergent if (convergent or finite) and not zerodiv: return ctx.gammaprod([c, c-a-b], [c-a, c-b], _infsign=True) # Otherwise, there is a pole and we take the # sign to be that when approaching from below # XXX: this evaluation is not necessarily correct in all cases return ctx.hyp2f1(a,b,c,1-ctx.eps*2) * ctx.inf # Equal to 1 (first term), unless there is a subsequent # division by zero if not z: # Division by zero but power of z is higher than # first order so cancels if c or a == 0 or b == 0: return 1+z # Indeterminate return ctx.nan # Hit zero denominator unless numerator goes to 0 first if ctx.isint(c) and c <= 0: if (ctx.isint(a) and c <= a <= 0) or \ (ctx.isint(b) and c <= b <= 0): pass else: # Pole in series return ctx.inf absz = abs(z) # Fast case: standard series converges rapidly, # possibly in finitely many terms if absz <= 0.8 or (ctx.isint(a) and a <= 0 and a >= -1000) or \ (ctx.isint(b) and b <= 0 and b >= -1000): return ctx.hypsum(2, 1, (atype, btype, ctype), [a, b, c], z, **kwargs) orig = ctx.prec try: ctx.prec += 10 # Use 1/z transformation if absz >= 1.3: def h(a,b): t = ctx.mpq_1-c; ab = a-b; rz = 1/z T1 = ([-z],[-a], [c,-ab],[b,c-a], [a,t+a],[ctx.mpq_1+ab], rz) T2 = ([-z],[-b], [c,ab],[a,c-b], [b,t+b],[ctx.mpq_1-ab], rz) return T1, T2 v = ctx.hypercomb(h, [a,b], **kwargs) # Use 1-z transformation elif abs(1-z) <= 0.75: def h(a,b): t = c-a-b; ca = c-a; cb = c-b; rz = 1-z T1 = [], [], [c,t], [ca,cb], [a,b], [1-t], rz T2 = [rz], [t], [c,a+b-c], [a,b], [ca,cb], [1+t], rz return T1, T2 v = ctx.hypercomb(h, [a,b], **kwargs) # Use z/(z-1) transformation elif abs(z/(z-1)) <= 0.75: v = ctx.hyp2f1(a, c-b, c, z/(z-1)) / (1-z)**a # Remaining part of unit circle else: v = _hyp2f1_gosper(ctx,a,b,c,z,**kwargs) finally: ctx.prec = orig return +v @defun def _hypq1fq(ctx, p, q, a_s, b_s, z, **kwargs): r""" Evaluates 3F2, 4F3, 5F4, ... """ a_s, a_types = zip(*a_s) b_s, b_types = zip(*b_s) a_s = list(a_s) b_s = list(b_s) absz = abs(z) ispoly = False for a in a_s: if ctx.isint(a) and a <= 0: ispoly = True break # Direct summation if absz < 1 or ispoly: try: return ctx.hypsum(p, q, a_types+b_types, a_s+b_s, z, **kwargs) except ctx.NoConvergence: if absz > 1.1 or ispoly: raise # Use expansion at |z-1| -> 0. # Reference: Wolfgang Buhring, "Generalized Hypergeometric Functions at # Unit Argument", Proc. Amer. Math. Soc., Vol. 114, No. 1 (Jan. 1992), # pp.145-153 # The current implementation has several problems: # 1. We only implement it for 3F2. The expansion coefficients are # given by extremely messy nested sums in the higher degree cases # (see reference). Is efficient sequential generation of the coefficients # possible in the > 3F2 case? # 2. Although the series converges, it may do so slowly, so we need # convergence acceleration. The acceleration implemented by # nsum does not always help, so results returned are sometimes # inaccurate! Can we do better? # 3. We should check conditions for convergence, and possibly # do a better job of cancelling out gamma poles if possible. if z == 1: # XXX: should also check for division by zero in the # denominator of the series (cf. hyp2f1) S = ctx.re(sum(b_s)-sum(a_s)) if S <= 0: #return ctx.hyper(a_s, b_s, 1-ctx.eps*2, **kwargs) * ctx.inf return ctx.hyper(a_s, b_s, 0.9, **kwargs) * ctx.inf if (p,q) == (3,2) and abs(z-1) < 0.05: # and kwargs.get('sum1') #print "Using alternate summation (experimental)" a1,a2,a3 = a_s b1,b2 = b_s u = b1+b2-a3 initial = ctx.gammaprod([b2-a3,b1-a3,a1,a2],[b2-a3,b1-a3,1,u]) def term(k, _cache={0:initial}): u = b1+b2-a3+k if k in _cache: t = _cache[k] else: t = _cache[k-1] t *= (b1+k-a3-1)*(b2+k-a3-1) t /= k*(u-1) _cache[k] = t return t * ctx.hyp2f1(a1,a2,u,z) try: S = ctx.nsum(term, [0,ctx.inf], verbose=kwargs.get('verbose'), strict=kwargs.get('strict', True)) return S * ctx.gammaprod([b1,b2],[a1,a2,a3]) except ctx.NoConvergence: pass # Try to use convergence acceleration on and close to the unit circle. # Problem: the convergence acceleration degenerates as |z-1| -> 0, # except for special cases. Everywhere else, the Shanks transformation # is very efficient. if absz < 1.1 and ctx._re(z) <= 1: def term(k, _cache={0:ctx.one}): k = int(k) if k in _cache: return _cache[k] t = _cache[k-1] m = k-1 for j in xrange(p): t *= (a_s[j]+m) for j in xrange(q): t /= (b_s[j]+m) t *= z t /= k _cache[k] = t return t return ctx.nsum(term, [0,ctx.inf], verbose=kwargs.get('verbose'), strict=kwargs.get('strict', True)) # Use 1/z transformation # http://functions.wolfram.com/HypergeometricFunctions/ # HypergeometricPFQ/06/01/05/02/0004/ def h(*args): a_s = list(args[:p]) b_s = list(args[p:]) Ts = [] recz = ctx.one/z negz = ctx.fneg(z, exact=True) for k in range(q+1): ak = a_s[k] C = [negz] Cp = [-ak] Gn = b_s + [ak] + [a_s[j]-ak for j in range(q+1) if j != k] Gd = a_s + [b_s[j]-ak for j in range(q)] Fn = [ak] + [ak-b_s[j]+1 for j in range(q)] Fd = [1-a_s[j]+ak for j in range(q+1) if j != k] Ts.append((C, Cp, Gn, Gd, Fn, Fd, recz)) return Ts return ctx.hypercomb(h, a_s+b_s, **kwargs) @defun def _hyp_borel(ctx, p, q, a_s, b_s, z, **kwargs): if a_s: a_s, a_types = zip(*a_s) a_s = list(a_s) else: a_s, a_types = [], () if b_s: b_s, b_types = zip(*b_s) b_s = list(b_s) else: b_s, b_types = [], () kwargs['maxterms'] = kwargs.get('maxterms', ctx.prec) try: return ctx.hypsum(p, q, a_types+b_types, a_s+b_s, z, **kwargs) except ctx.NoConvergence: pass prec = ctx.prec try: tol = kwargs.get('asymp_tol', ctx.eps/4) ctx.prec += 10 # hypsum is has a conservative tolerance. So we try again: def term(k, cache={0:ctx.one}): if k in cache: return cache[k] t = term(k-1) for a in a_s: t *= (a+(k-1)) for b in b_s: t /= (b+(k-1)) t *= z t /= k cache[k] = t return t s = ctx.one for k in xrange(1, ctx.prec): t = term(k) s += t if abs(t) <= tol: return s finally: ctx.prec = prec if p <= q+3: contour = kwargs.get('contour') if not contour: if ctx.arg(z) < 0.25: u = z / max(1, abs(z)) if ctx.arg(z) >= 0: contour = [0, 2j, (2j+2)/u, 2/u, ctx.inf] else: contour = [0, -2j, (-2j+2)/u, 2/u, ctx.inf] #contour = [0, 2j/z, 2/z, ctx.inf] #contour = [0, 2j, 2/z, ctx.inf] #contour = [0, 2j, ctx.inf] else: contour = [0, ctx.inf] quad_kwargs = kwargs.get('quad_kwargs', {}) def g(t): return ctx.exp(-t)*ctx.hyper(a_s, b_s+[1], t*z) I, err = ctx.quad(g, contour, error=True, **quad_kwargs) if err <= abs(I)*ctx.eps*8: return I raise ctx.NoConvergence @defun def _hyp2f2(ctx, a_s, b_s, z, **kwargs): (a1, a1type), (a2, a2type) = a_s (b1, b1type), (b2, b2type) = b_s absz = abs(z) magz = ctx.mag(z) orig = ctx.prec # Asymptotic expansion is ~ exp(z) asymp_extraprec = magz # Asymptotic series is in terms of 3F1 can_use_asymptotic = (not kwargs.get('force_series')) and \ (ctx.mag(absz) > 3) # TODO: much of the following could be shared with 2F3 instead of # copypasted if can_use_asymptotic: #print "using asymp" try: try: ctx.prec += asymp_extraprec # http://functions.wolfram.com/HypergeometricFunctions/ # Hypergeometric2F2/06/02/02/0002/ def h(a1,a2,b1,b2): X = a1+a2-b1-b2 A2 = a1+a2 B2 = b1+b2 c = {} c[0] = ctx.one c[1] = (A2-1)*X+b1*b2-a1*a2 s1 = 0 k = 0 tprev = 0 while 1: if k not in c: uu1 = 1-B2+2*a1+a1**2+2*a2+a2**2-A2*B2+a1*a2+b1*b2+(2*B2-3*(A2+1))*k+2*k**2 uu2 = (k-A2+b1-1)*(k-A2+b2-1)*(k-X-2) c[k] = ctx.one/k * (uu1*c[k-1]-uu2*c[k-2]) t1 = c[k] * z**(-k) if abs(t1) < 0.1*ctx.eps: #print "Convergence :)" break # Quit if the series doesn't converge quickly enough if k > 5 and abs(tprev) / abs(t1) < 1.5: #print "No convergence :(" raise ctx.NoConvergence s1 += t1 tprev = t1 k += 1 S = ctx.exp(z)*s1 T1 = [z,S], [X,1], [b1,b2],[a1,a2],[],[],0 T2 = [-z],[-a1],[b1,b2,a2-a1],[a2,b1-a1,b2-a1],[a1,a1-b1+1,a1-b2+1],[a1-a2+1],-1/z T3 = [-z],[-a2],[b1,b2,a1-a2],[a1,b1-a2,b2-a2],[a2,a2-b1+1,a2-b2+1],[-a1+a2+1],-1/z return T1, T2, T3 v = ctx.hypercomb(h, [a1,a2,b1,b2], force_series=True, maxterms=4*ctx.prec) if sum(ctx._is_real_type(u) for u in [a1,a2,b1,b2,z]) == 5: v = ctx.re(v) return v except ctx.NoConvergence: pass finally: ctx.prec = orig return ctx.hypsum(2, 2, (a1type, a2type, b1type, b2type), [a1, a2, b1, b2], z, **kwargs) @defun def _hyp1f2(ctx, a_s, b_s, z, **kwargs): (a1, a1type), = a_s (b1, b1type), (b2, b2type) = b_s absz = abs(z) magz = ctx.mag(z) orig = ctx.prec # Asymptotic expansion is ~ exp(sqrt(z)) asymp_extraprec = z and magz//2 # Asymptotic series is in terms of 3F0 can_use_asymptotic = (not kwargs.get('force_series')) and \ (ctx.mag(absz) > 19) and \ (ctx.sqrt(absz) > 1.5*orig) #and \ #ctx._hyp_check_convergence([a1, a1-b1+1, a1-b2+1], [], # 1/absz, orig+40+asymp_extraprec) # TODO: much of the following could be shared with 2F3 instead of # copypasted if can_use_asymptotic: #print "using asymp" try: try: ctx.prec += asymp_extraprec # http://functions.wolfram.com/HypergeometricFunctions/ # Hypergeometric1F2/06/02/03/ def h(a1,b1,b2): X = ctx.mpq_1_2*(a1-b1-b2+ctx.mpq_1_2) c = {} c[0] = ctx.one c[1] = 2*(ctx.mpq_1_4*(3*a1+b1+b2-2)*(a1-b1-b2)+b1*b2-ctx.mpq_3_16) c[2] = 2*(b1*b2+ctx.mpq_1_4*(a1-b1-b2)*(3*a1+b1+b2-2)-ctx.mpq_3_16)**2+\ ctx.mpq_1_16*(-16*(2*a1-3)*b1*b2 + \ 4*(a1-b1-b2)*(-8*a1**2+11*a1+b1+b2-2)-3) s1 = 0 s2 = 0 k = 0 tprev = 0 while 1: if k not in c: uu1 = (3*k**2+(-6*a1+2*b1+2*b2-4)*k + 3*a1**2 - \ (b1-b2)**2 - 2*a1*(b1+b2-2) + ctx.mpq_1_4) uu2 = (k-a1+b1-b2-ctx.mpq_1_2)*(k-a1-b1+b2-ctx.mpq_1_2)*\ (k-a1+b1+b2-ctx.mpq_5_2) c[k] = ctx.one/(2*k)*(uu1*c[k-1]-uu2*c[k-2]) w = c[k] * (-z)**(-0.5*k) t1 = (-ctx.j)**k * ctx.mpf(2)**(-k) * w t2 = ctx.j**k * ctx.mpf(2)**(-k) * w if abs(t1) < 0.1*ctx.eps: #print "Convergence :)" break # Quit if the series doesn't converge quickly enough if k > 5 and abs(tprev) / abs(t1) < 1.5: #print "No convergence :(" raise ctx.NoConvergence s1 += t1 s2 += t2 tprev = t1 k += 1 S = ctx.expj(ctx.pi*X+2*ctx.sqrt(-z))*s1 + \ ctx.expj(-(ctx.pi*X+2*ctx.sqrt(-z)))*s2 T1 = [0.5*S, ctx.pi, -z], [1, -0.5, X], [b1, b2], [a1],\ [], [], 0 T2 = [-z], [-a1], [b1,b2],[b1-a1,b2-a1], \ [a1,a1-b1+1,a1-b2+1], [], 1/z return T1, T2 v = ctx.hypercomb(h, [a1,b1,b2], force_series=True, maxterms=4*ctx.prec) if sum(ctx._is_real_type(u) for u in [a1,b1,b2,z]) == 4: v = ctx.re(v) return v except ctx.NoConvergence: pass finally: ctx.prec = orig #print "not using asymp" return ctx.hypsum(1, 2, (a1type, b1type, b2type), [a1, b1, b2], z, **kwargs) @defun def _hyp2f3(ctx, a_s, b_s, z, **kwargs): (a1, a1type), (a2, a2type) = a_s (b1, b1type), (b2, b2type), (b3, b3type) = b_s absz = abs(z) magz = ctx.mag(z) # Asymptotic expansion is ~ exp(sqrt(z)) asymp_extraprec = z and magz//2 orig = ctx.prec # Asymptotic series is in terms of 4F1 # The square root below empirically provides a plausible criterion # for the leading series to converge can_use_asymptotic = (not kwargs.get('force_series')) and \ (ctx.mag(absz) > 19) and (ctx.sqrt(absz) > 1.5*orig) if can_use_asymptotic: #print "using asymp" try: try: ctx.prec += asymp_extraprec # http://functions.wolfram.com/HypergeometricFunctions/ # Hypergeometric2F3/06/02/03/01/0002/ def h(a1,a2,b1,b2,b3): X = ctx.mpq_1_2*(a1+a2-b1-b2-b3+ctx.mpq_1_2) A2 = a1+a2 B3 = b1+b2+b3 A = a1*a2 B = b1*b2+b3*b2+b1*b3 R = b1*b2*b3 c = {} c[0] = ctx.one c[1] = 2*(B - A + ctx.mpq_1_4*(3*A2+B3-2)*(A2-B3) - ctx.mpq_3_16) c[2] = ctx.mpq_1_2*c[1]**2 + ctx.mpq_1_16*(-16*(2*A2-3)*(B-A) + 32*R +\ 4*(-8*A2**2 + 11*A2 + 8*A + B3 - 2)*(A2-B3)-3) s1 = 0 s2 = 0 k = 0 tprev = 0 while 1: if k not in c: uu1 = (k-2*X-3)*(k-2*X-2*b1-1)*(k-2*X-2*b2-1)*\ (k-2*X-2*b3-1) uu2 = (4*(k-1)**3 - 6*(4*X+B3)*(k-1)**2 + \ 2*(24*X**2+12*B3*X+4*B+B3-1)*(k-1) - 32*X**3 - \ 24*B3*X**2 - 4*B - 8*R - 4*(4*B+B3-1)*X + 2*B3-1) uu3 = (5*(k-1)**2+2*(-10*X+A2-3*B3+3)*(k-1)+2*c[1]) c[k] = ctx.one/(2*k)*(uu1*c[k-3]-uu2*c[k-2]+uu3*c[k-1]) w = c[k] * ctx.power(-z, -0.5*k) t1 = (-ctx.j)**k * ctx.mpf(2)**(-k) * w t2 = ctx.j**k * ctx.mpf(2)**(-k) * w if abs(t1) < 0.1*ctx.eps: break # Quit if the series doesn't converge quickly enough if k > 5 and abs(tprev) / abs(t1) < 1.5: raise ctx.NoConvergence s1 += t1 s2 += t2 tprev = t1 k += 1 S = ctx.expj(ctx.pi*X+2*ctx.sqrt(-z))*s1 + \ ctx.expj(-(ctx.pi*X+2*ctx.sqrt(-z)))*s2 T1 = [0.5*S, ctx.pi, -z], [1, -0.5, X], [b1, b2, b3], [a1, a2],\ [], [], 0 T2 = [-z], [-a1], [b1,b2,b3,a2-a1],[a2,b1-a1,b2-a1,b3-a1], \ [a1,a1-b1+1,a1-b2+1,a1-b3+1], [a1-a2+1], 1/z T3 = [-z], [-a2], [b1,b2,b3,a1-a2],[a1,b1-a2,b2-a2,b3-a2], \ [a2,a2-b1+1,a2-b2+1,a2-b3+1],[-a1+a2+1], 1/z return T1, T2, T3 v = ctx.hypercomb(h, [a1,a2,b1,b2,b3], force_series=True, maxterms=4*ctx.prec) if sum(ctx._is_real_type(u) for u in [a1,a2,b1,b2,b3,z]) == 6: v = ctx.re(v) return v except ctx.NoConvergence: pass finally: ctx.prec = orig return ctx.hypsum(2, 3, (a1type, a2type, b1type, b2type, b3type), [a1, a2, b1, b2, b3], z, **kwargs) @defun def _hyp2f0(ctx, a_s, b_s, z, **kwargs): (a, atype), (b, btype) = a_s # We want to try aggressively to use the asymptotic expansion, # and fall back only when absolutely necessary try: kwargsb = kwargs.copy() kwargsb['maxterms'] = kwargsb.get('maxterms', ctx.prec) return ctx.hypsum(2, 0, (atype,btype), [a,b], z, **kwargsb) except ctx.NoConvergence: if kwargs.get('force_series'): raise pass def h(a, b): w = ctx.sinpi(b) rz = -1/z T1 = ([ctx.pi,w,rz],[1,-1,a],[],[a-b+1,b],[a],[b],rz) T2 = ([-ctx.pi,w,rz],[1,-1,1+a-b],[],[a,2-b],[a-b+1],[2-b],rz) return T1, T2 return ctx.hypercomb(h, [a, 1+a-b], **kwargs) @defun def hyperu(ctx, a, b, z, **kwargs): a, atype = ctx._convert_param(a) b, btype = ctx._convert_param(b) z = ctx.convert(z) if not z: if ctx.re(b) <= 1: return ctx.gammaprod([1-b],[a-b+1]) else: return ctx.inf + z bb = 1+a-b bb, bbtype = ctx._convert_param(bb) try: orig = ctx.prec try: ctx.prec += 10 v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec) return v / z**a finally: ctx.prec = orig except ctx.NoConvergence: pass def h(a,b): w = ctx.sinpi(b) T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z) T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z) return T1, T2 return ctx.hypercomb(h, [a,b], **kwargs) @defun_wrapped def _erf_complex(ctx, z): z2 = ctx.square_exp_arg(z, -1) #z2 = -z**2 v = (2/ctx.sqrt(ctx.pi))*z * ctx.hyp1f1((1,2),(3,2), z2) if not ctx._re(z): v = ctx._im(v)*ctx.j return v @defun_wrapped def _erfc_complex(ctx, z): if ctx.re(z) > 2: z2 = ctx.square_exp_arg(z) nz2 = ctx.fneg(z2, exact=True) v = ctx.exp(nz2)/ctx.sqrt(ctx.pi) * ctx.hyperu((1,2),(1,2), z2) else: v = 1 - ctx._erf_complex(z) if not ctx._re(z): v = 1+ctx._im(v)*ctx.j return v @defun def erf(ctx, z): z = ctx.convert(z) if ctx._is_real_type(z): try: return ctx._erf(z) except NotImplementedError: pass if ctx._is_complex_type(z) and not z.imag: try: return type(z)(ctx._erf(z.real)) except NotImplementedError: pass return ctx._erf_complex(z) @defun def erfc(ctx, z): z = ctx.convert(z) if ctx._is_real_type(z): try: return ctx._erfc(z) except NotImplementedError: pass if ctx._is_complex_type(z) and not z.imag: try: return type(z)(ctx._erfc(z.real)) except NotImplementedError: pass return ctx._erfc_complex(z) @defun def square_exp_arg(ctx, z, mult=1, reciprocal=False): prec = ctx.prec*4+20 if reciprocal: z2 = ctx.fmul(z, z, prec=prec) z2 = ctx.fdiv(ctx.one, z2, prec=prec) else: z2 = ctx.fmul(z, z, prec=prec) if mult != 1: z2 = ctx.fmul(z2, mult, exact=True) return z2 @defun_wrapped def erfi(ctx, z): if not z: return z z2 = ctx.square_exp_arg(z) v = (2/ctx.sqrt(ctx.pi)*z) * ctx.hyp1f1((1,2), (3,2), z2) if not ctx._re(z): v = ctx._im(v)*ctx.j return v @defun_wrapped def erfinv(ctx, x): xre = ctx._re(x) if (xre != x) or (xre < -1) or (xre > 1): return ctx.bad_domain("erfinv(x) is defined only for -1 <= x <= 1") x = xre #if ctx.isnan(x): return x if not x: return x if x == 1: return ctx.inf if x == -1: return ctx.ninf if abs(x) < 0.9: a = 0.53728*x**3 + 0.813198*x else: # An asymptotic formula u = ctx.ln(2/ctx.pi/(abs(x)-1)**2) a = ctx.sign(x) * ctx.sqrt(u - ctx.ln(u))/ctx.sqrt(2) ctx.prec += 10 return ctx.findroot(lambda t: ctx.erf(t)-x, a) @defun_wrapped def npdf(ctx, x, mu=0, sigma=1): sigma = ctx.convert(sigma) return ctx.exp(-(x-mu)**2/(2*sigma**2)) / (sigma*ctx.sqrt(2*ctx.pi)) @defun_wrapped def ncdf(ctx, x, mu=0, sigma=1): a = (x-mu)/(sigma*ctx.sqrt(2)) if a < 0: return ctx.erfc(-a)/2 else: return (1+ctx.erf(a))/2 @defun_wrapped def betainc(ctx, a, b, x1=0, x2=1, regularized=False): if x1 == x2: v = 0 elif not x1: if x1 == 0 and x2 == 1: v = ctx.beta(a, b) else: v = x2**a * ctx.hyp2f1(a, 1-b, a+1, x2) / a else: m, d = ctx.nint_distance(a) if m <= 0: if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 a += h elif d < -4: ctx.prec -= d s1 = x2**a * ctx.hyp2f1(a,1-b,a+1,x2) s2 = x1**a * ctx.hyp2f1(a,1-b,a+1,x1) v = (s1 - s2) / a if regularized: v /= ctx.beta(a,b) return v @defun def gammainc(ctx, z, a=0, b=None, regularized=False): regularized = bool(regularized) z = ctx.convert(z) if a is None: a = ctx.zero lower_modified = False else: a = ctx.convert(a) lower_modified = a != ctx.zero if b is None: b = ctx.inf upper_modified = False else: b = ctx.convert(b) upper_modified = b != ctx.inf # Complete gamma function if not (upper_modified or lower_modified): if regularized: if ctx.re(z) < 0: return ctx.inf elif ctx.re(z) > 0: return ctx.one else: return ctx.nan return ctx.gamma(z) if a == b: return ctx.zero # Standardize if ctx.re(a) > ctx.re(b): return -ctx.gammainc(z, b, a, regularized) # Generalized gamma if upper_modified and lower_modified: return +ctx._gamma3(z, a, b, regularized) # Upper gamma elif lower_modified: return ctx._upper_gamma(z, a, regularized) # Lower gamma elif upper_modified: return ctx._lower_gamma(z, b, regularized) @defun def _lower_gamma(ctx, z, b, regularized=False): # Pole if ctx.isnpint(z): return type(z)(ctx.inf) G = [z] * regularized negb = ctx.fneg(b, exact=True) def h(z): T1 = [ctx.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b return (T1,) return ctx.hypercomb(h, [z]) @defun def _upper_gamma(ctx, z, a, regularized=False): # Fast integer case, when available if ctx.isint(z): try: if regularized: # Gamma pole if ctx.isnpint(z): return type(z)(ctx.zero) orig = ctx.prec try: ctx.prec += 10 return ctx._gamma_upper_int(z, a) / ctx.gamma(z) finally: ctx.prec = orig else: return ctx._gamma_upper_int(z, a) except NotImplementedError: pass nega = ctx.fneg(a, exact=True) G = [z] * regularized # Use 2F0 series when possible; fall back to lower gamma representation try: def h(z): r = z-1 return [([ctx.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] return ctx.hypercomb(h, [z], force_series=True) except ctx.NoConvergence: def h(z): T1 = [], [1, z-1], [z], G, [], [], 0 T2 = [-ctx.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a return T1, T2 return ctx.hypercomb(h, [z]) @defun def _gamma3(ctx, z, a, b, regularized=False): pole = ctx.isnpint(z) if regularized and pole: return ctx.zero try: ctx.prec += 15 # We don't know in advance whether it's better to write as a difference # of lower or upper gamma functions, so try both T1 = ctx.gammainc(z, a, regularized=regularized) T2 = ctx.gammainc(z, b, regularized=regularized) R = T1 - T2 if ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: return R if not pole: T1 = ctx.gammainc(z, 0, b, regularized=regularized) T2 = ctx.gammainc(z, 0, a, regularized=regularized) R = T1 - T2 # May be ok, but should probably at least print a warning # about possible cancellation if 1: #ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: return R finally: ctx.prec -= 15 raise NotImplementedError @defun_wrapped def expint(ctx, n, z): if ctx.isint(n) and ctx._is_real_type(z): try: return ctx._expint_int(n, z) except NotImplementedError: pass if ctx.isnan(n) or ctx.isnan(z): return z*n if z == ctx.inf: return 1/z if z == 0: # integral from 1 to infinity of t^n if ctx.re(n) <= 1: # TODO: reasonable sign of infinity return type(z)(ctx.inf) else: return ctx.one/(n-1) if n == 0: return ctx.exp(-z)/z if n == -1: return ctx.exp(-z)*(z+1)/z**2 return z**(n-1) * ctx.gammainc(1-n, z) @defun_wrapped def li(ctx, z, offset=False): if offset: if z == 2: return ctx.zero return ctx.ei(ctx.ln(z)) - ctx.ei(ctx.ln2) if not z: return z if z == 1: return ctx.ninf return ctx.ei(ctx.ln(z)) @defun def ei(ctx, z): try: return ctx._ei(z) except NotImplementedError: return ctx._ei_generic(z) @defun_wrapped def _ei_generic(ctx, z): # Note: the following is currently untested because mp and fp # both use special-case ei code if z == ctx.inf: return z if z == ctx.ninf: return ctx.zero if ctx.mag(z) > 1: try: r = ctx.one/z v = ctx.exp(z)*ctx.hyper([1,1],[],r, maxterms=ctx.prec, force_series=True)/z im = ctx._im(z) if im > 0: v += ctx.pi*ctx.j if im < 0: v -= ctx.pi*ctx.j return v except ctx.NoConvergence: pass v = z*ctx.hyp2f2(1,1,2,2,z) + ctx.euler if ctx._im(z): v += 0.5*(ctx.log(z) - ctx.log(ctx.one/z)) else: v += ctx.log(abs(z)) return v @defun def e1(ctx, z): try: return ctx._e1(z) except NotImplementedError: return ctx.expint(1, z) @defun def ci(ctx, z): try: return ctx._ci(z) except NotImplementedError: return ctx._ci_generic(z) @defun_wrapped def _ci_generic(ctx, z): if ctx.isinf(z): if z == ctx.inf: return ctx.zero if z == ctx.ninf: return ctx.pi*1j jz = ctx.fmul(ctx.j,z,exact=True) njz = ctx.fneg(jz,exact=True) v = 0.5*(ctx.ei(jz) + ctx.ei(njz)) zreal = ctx._re(z) zimag = ctx._im(z) if zreal == 0: if zimag > 0: v += ctx.pi*0.5j if zimag < 0: v -= ctx.pi*0.5j if zreal < 0: if zimag >= 0: v += ctx.pi*1j if zimag < 0: v -= ctx.pi*1j if ctx._is_real_type(z) and zreal > 0: v = ctx._re(v) return v @defun def si(ctx, z): try: return ctx._si(z) except NotImplementedError: return ctx._si_generic(z) @defun_wrapped def _si_generic(ctx, z): if ctx.isinf(z): if z == ctx.inf: return 0.5*ctx.pi if z == ctx.ninf: return -0.5*ctx.pi # Suffers from cancellation near 0 if ctx.mag(z) >= -1: jz = ctx.fmul(ctx.j,z,exact=True) njz = ctx.fneg(jz,exact=True) v = (-0.5j)*(ctx.ei(jz) - ctx.ei(njz)) zreal = ctx._re(z) if zreal > 0: v -= 0.5*ctx.pi if zreal < 0: v += 0.5*ctx.pi if ctx._is_real_type(z): v = ctx._re(v) return v else: return z*ctx.hyp1f2((1,2),(3,2),(3,2),-0.25*z*z) @defun_wrapped def chi(ctx, z): nz = ctx.fneg(z, exact=True) v = 0.5*(ctx.ei(z) + ctx.ei(nz)) zreal = ctx._re(z) zimag = ctx._im(z) if zimag > 0: v += ctx.pi*0.5j elif zimag < 0: v -= ctx.pi*0.5j elif zreal < 0: v += ctx.pi*1j return v @defun_wrapped def shi(ctx, z): # Suffers from cancellation near 0 if ctx.mag(z) >= -1: nz = ctx.fneg(z, exact=True) v = 0.5*(ctx.ei(z) - ctx.ei(nz)) zimag = ctx._im(z) if zimag > 0: v -= 0.5j*ctx.pi if zimag < 0: v += 0.5j*ctx.pi return v else: return z * ctx.hyp1f2((1,2),(3,2),(3,2),0.25*z*z) @defun_wrapped def fresnels(ctx, z): if z == ctx.inf: return ctx.mpf(0.5) if z == ctx.ninf: return ctx.mpf(-0.5) return ctx.pi*z**3/6*ctx.hyp1f2((3,4),(3,2),(7,4),-ctx.pi**2*z**4/16) @defun_wrapped def fresnelc(ctx, z): if z == ctx.inf: return ctx.mpf(0.5) if z == ctx.ninf: return ctx.mpf(-0.5) return z*ctx.hyp1f2((1,4),(1,2),(5,4),-ctx.pi**2*z**4/16) @defun_wrapped def airyai(ctx, z): if z == ctx.inf or z == ctx.ninf: return ctx.zero if z: # Account for exponential scaling ctx.prec += max(0, int(1.5*ctx.mag(z))) if ctx._re(z) > 4: # We could still use 1F1, but it results in huge cancellation; # the following expansion is better w = z**1.5 r = -ctx.mpf(3)/(4*w) v = ctx.exp(-2*w/3)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4)) v *= ctx.hyp2f0((1,6),(5,6),r) return v elif ctx._re(z) > 1: # If not using asymptotic series: # cancellation: both terms are ~ 2^(z^1.5), # result is ~ 2^(-z^1.5), so need ~2*z^1.5 extra bits ctx.prec += 2*int(ctx._re(z)**1.5) z3 = z**3 / 9 a = ctx.hyp0f1((2,3), z3) / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3)) b = z * ctx.hyp0f1((4,3), z3) / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3)) return a - b @defun_wrapped def airybi(ctx, z): if z == ctx.inf: return z if z == ctx.ninf: return 1/z if z: # Account for exponential scaling ctx.prec += max(0, int(1.5*ctx.mag(z))) z3 = z**3 / 9 rt = ctx.nthroot(3, 6) a = ctx.hyp0f1((2,3), z3) / (rt * ctx.gamma(ctx.mpf(2)/3)) b = z * rt * ctx.hyp0f1((4,3), z3) / ctx.gamma(ctx.mpf(1)/3) return a + b @defun_wrapped def hermite(ctx, n, z, **kwargs): if not z: try: return 2**n * ctx.sqrt(ctx.pi) / ctx.gamma(0.5*(1-n)) except ValueError: return 0.0*(n+z) if ctx.re(z) > 0 or (ctx.re(z) == 0 and ctx.im(z) > 0) or ctx.isnpint(-n): prec = ctx.prec ctx.prec = ctx.prec*4+20 z2 = -z**(-2) ctx.prec = prec return (2*z)**n * ctx.hyp2f0(-0.5*n, -0.5*(n-1), z2, **kwargs) else: prec = ctx.prec ctx.prec = ctx.prec*4+20 z2 = z**2 ctx.prec = prec return ctx.hermite(n,-z) + 2**(n+2)*ctx.sqrt(ctx.pi) * (-z) / \ ctx.gamma(-0.5*n) * ctx.hyp1f1((1-n)*0.5, 1.5, z2, **kwargs) @defun_wrapped def gegenbauer(ctx, n, a, z, **kwargs): # Special cases: a+0.5, a*2 poles if ctx.isnpint(a): return 0*(z+n) if ctx.isnpint(a+0.5): # TODO: something else is required here # E.g.: gegenbauer(-2, -0.5, 3) == -12 if ctx.isnpint(n+1): raise NotImplementedError("Gegenbauer function with two limits") def h(a): a2 = 2*a T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) return [T] return ctx.hypercomb(h, [a], **kwargs) def h(n): a2 = 2*a T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) return [T] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def jacobi(ctx, n, a, b, x, **kwargs): if not ctx.isnpint(a): def h(n): return (([], [], [a+n+1], [n+1, a+1], [-n, a+b+n+1], [a+1], (1-x)*0.5),) return ctx.hypercomb(h, [n], **kwargs) if not ctx.isint(b): def h(n, a): return (([], [], [-b], [n+1, -b-n], [-n, a+b+n+1], [b+1], (x+1)*0.5),) return ctx.hypercomb(h, [n, a], **kwargs) # XXX: determine appropriate limit return ctx.binomial(n+a,n) * ctx.hyp2f1(-n,1+n+a+b,a+1,(1-x)/2, **kwargs) @defun_wrapped def laguerre(ctx, n, a, z, **kwargs): # XXX: limits, poles #if ctx.isnpint(n): # return 0*(a+z) def h(a): return (([], [], [a+n+1], [a+1, n+1], [-n], [a+1], z),) return ctx.hypercomb(h, [a], **kwargs) @defun_wrapped def legendre(ctx, n, x, **kwargs): if ctx.isint(n): n = int(n) # Accuracy near zeros if (n + (n < 0)) & 1: if not x: return x mag = ctx.mag(x) if mag < -2*ctx.prec-10: return x if mag < -5: ctx.prec += -mag return ctx.hyp2f1(-n,n+1,1,(1-x)/2, **kwargs) @defun def legenp(ctx, n, m, z, type=2, **kwargs): # Legendre function, 1st kind n = ctx.convert(n) m = ctx.convert(m) # Faster if not m: return ctx.legendre(n, z, **kwargs) # TODO: correct evaluation at singularities if type == 2: def h(n,m): g = m*0.5 T = [1+z, 1-z], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) return (T,) return ctx.hypercomb(h, [n,m], **kwargs) if type == 3: def h(n,m): g = m*0.5 T = [z+1, z-1], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) return (T,) return ctx.hypercomb(h, [n,m], **kwargs) raise ValueError("requires type=2 or type=3") @defun def legenq(ctx, n, m, z, type=2, **kwargs): # Legendre function, 2nd kind n = ctx.convert(n) m = ctx.convert(m) z = ctx.convert(z) if z in (1, -1): #if ctx.isint(m): # return ctx.nan #return ctx.inf # unsigned return ctx.nan if type == 2: def h(n, m): s = 2 * ctx.sinpi(m) / ctx.pi c = ctx.cospi(m) a = 1+z b = 1-z u = m/2 w = (1-z)/2 T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ [-n, n+1], [1-m], w T2 = [-s, a, b], [-1, -u, u], [n+m+1], [n-m+1, m+1], \ [-n, n+1], [m+1], w return T1, T2 return ctx.hypercomb(h, [n, m], **kwargs) if type == 3: # The following is faster when there only is a single series # Note: not valid for -1 < z < 0 (?) if abs(z) > 1: def h(n, m): T1 = [ctx.expjpi(m), 2, ctx.pi, z, z-1, z+1], \ [1, -n-1, 0.5, -n-m-1, 0.5*m, 0.5*m], \ [n+m+1], [n+1.5], \ [0.5*(2+n+m), 0.5*(1+n+m)], [n+1.5], z**(-2) return [T1] return ctx.hypercomb(h, [n, m], **kwargs) else: # not valid for 1 < z < inf ? def h(n, m): s = 2 * ctx.sinpi(m) / ctx.pi c = ctx.expjpi(m) a = 1+z b = z-1 u = m/2 w = (1-z)/2 T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ [-n, n+1], [1-m], w T2 = [-s, c, a, b], [-1, 1, -u, u], [n+m+1], [n-m+1, m+1], \ [-n, n+1], [m+1], w return T1, T2 return ctx.hypercomb(h, [n, m], **kwargs) raise ValueError("requires type=2 or type=3") @defun_wrapped def chebyt(ctx, n, x, **kwargs): return ctx.hyp2f1(-n,n,(1,2),(1-x)/2, **kwargs) @defun_wrapped def chebyu(ctx, n, x, **kwargs): return (n+1) * ctx.hyp2f1(-n, n+2, (3,2), (1-x)/2, **kwargs) @defun def j0(ctx, x): """Computes the Bessel function `J_0(x)`. See :func:`besselj`.""" return ctx.besselj(0, x) @defun def j1(ctx, x): """Computes the Bessel function `J_1(x)`. See :func:`besselj`.""" return ctx.besselj(1, x) @defun def besselj(ctx, n, z, derivative=0, **kwargs): if type(n) is int: n_isint = True else: n = ctx.convert(n) n_isint = ctx.isint(n) if n_isint: n = int(n) if n_isint and n < 0: return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs) z = ctx.convert(z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) # TODO: the integer special-casing shouldn't be necessary. # However, the hypergeometric series gets inaccurate for large d # because of inaccurate pole cancellation at a pole far from # zero (needs to be fixed in hypercomb or hypsum) if ctx.isint(d) and d >= 0: d = int(d) orig = ctx.prec try: ctx.prec += 15 v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z) for k in range(d+1)) finally: ctx.prec = orig v *= ctx.mpf(2)**(-d) else: def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2)] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20: try: return ctx._besselj(n, z) except NotImplementedError: pass if not z: if not n: v = ctx.one + n+z elif ctx.re(n) > 0: v = n*z else: v = ctx.inf + z + n else: #v = 0 orig = ctx.prec try: # XXX: workaround for accuracy in low level hypergeometric series # when alternating, large arguments ctx.prec += min(3*abs(M), ctx.prec) w = ctx.fmul(z, 0.5, exact=True) def h(n): r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) finally: ctx.prec = orig v = +v return v @defun def besseli(ctx, n, z, derivative=0, **kwargs): n = ctx.convert(n) z = ctx.convert(z) if not z: if derivative: raise ValueError if not n: # I(0,0) = 1 return 1+n+z if ctx.isint(n): return 0*(n+z) r = ctx.re(n) if r == 0: return ctx.nan*(n+z) elif r > 0: return 0*(n+z) else: return ctx.inf+(n+z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2), n+1] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: def h(n): w = ctx.fmul(z, 0.5, exact=True) r = ctx.fmul(w, w, prec=max(0,ctx.prec+M)) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) return v @defun_wrapped def bessely(ctx, n, z, derivative=0, **kwargs): if not z: if derivative: # Not implemented raise ValueError if not n: # ~ log(z/2) return -ctx.inf + (n+z) if ctx.im(n): return nan * (n+z) r = ctx.re(n) q = n+0.5 if ctx.isint(q): if n > 0: return -ctx.inf + (n+z) else: return 0 * (n+z) if r < 0 and int(ctx.floor(q)) % 2: return ctx.inf + (n+z) else: return ctx.ninf + (n+z) # XXX: use hypercomb ctx.prec += 10 m, d = ctx.nint_distance(n) if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 n += h elif d < 0: ctx.prec -= d # TODO: avoid cancellation for imaginary arguments return (ctx.besselj(n,z,derivative,**kwargs)*ctx.cospi(n) - \ ctx.besselj(-n,z,derivative,**kwargs))/ctx.sinpi(n) @defun_wrapped def besselk(ctx, n, z, **kwargs): if not z: return ctx.inf M = ctx.mag(z) if M < 1: # Represent as limit definition def h(n): r = (z/2)**2 T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r return T1, T2 # We could use the limit definition always, but it leads # to very bad cancellation (of exponentially large terms) # for large real z # Instead represent in terms of 2F0 else: ctx.prec += M def h(n): return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \ [n+0.5, 0.5-n], [], -1/(2*z))] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def hankel1(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def hankel2(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def whitm(ctx,k,m,z,**kwargs): if z == 0: # M(k,m,z) = 0^(1/2+m) if ctx.re(m) > -0.5: return z elif ctx.re(m) < -0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs) @defun_wrapped def whitw(ctx,k,m,z,**kwargs): if z == 0: g = abs(ctx.re(m)) if g < 0.5: return z elif g > 0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs) @defun def struveh(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) @defun def struvel(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) @defun def ber(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/ def h(n): r = -(z/4)**4 T1 = [ctx.cospi(0.75*n), z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r T2 = [-ctx.sinpi(0.75*n), z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def bei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/ def h(n): r = -(z/4)**4 T1 = [ctx.cospi(0.75*n), z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r T2 = [ctx.sinpi(0.75*n), z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def ker(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/ def h(n): r = -(z/4)**4 T1 = [2, z, 4*ctx.cospi(0.25*n)], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r T2 = [2, z, -ctx.sinpi(0.25*n)], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r T3 = [2, z, 4*ctx.cospi(0.75*n)], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T4 = [2, z, -ctx.sinpi(0.75*n)], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) @defun def kei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/ def h(n): r = -(z/4)**4 T1 = [-ctx.cospi(0.75*n), 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r T2 = [-ctx.sinpi(0.75*n), 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T3 = [-ctx.sinpi(0.25*n), 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r T4 = [-ctx.cospi(0.25*n), 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) @defun def meijerg(ctx, a_s, b_s, z, r=1, series=None, **kwargs): an, ap = a_s bm, bq = b_s n = len(an) p = n + len(ap) m = len(bm) q = m + len(bq) a = an+ap b = bm+bq a = map(ctx.convert, a) b = map(ctx.convert, b) z = ctx.convert(z) if series is None: if p < q: series = 1 if p > q: series = 2 if p == q: if m+n == p and abs(z) > 1: series = 2 else: series = 1 if kwargs.get('verbose'): print "Meijer G m,n,p,q,series =", m,n,p,q,series if series == 1: def h(*args): a = args[:p] b = args[p:] terms = [] for k in range(m): bases = [z] expts = [b[k]/r] gn = [b[j]-b[k] for j in range(m) if j != k] gn += [1-a[j]+b[k] for j in range(n)] gd = [a[j]-b[k] for j in range(n,p)] gd += [1-b[j]+b[k] for j in range(m,q)] hn = [1-a[j]+b[k] for j in range(p)] hd = [1-b[j]+b[k] for j in range(q) if j != k] hz = (-ctx.one)**(p-m-n) * z**(ctx.one/r) terms.append((bases, expts, gn, gd, hn, hd, hz)) return terms else: def h(*args): a = args[:p] b = args[p:] terms = [] for k in range(n): bases = [z] if r == 1: expts = [a[k]-1] else: expts = [(a[k]-1)/ctx.convert(r)] gn = [a[k]-a[j] for j in range(n) if j != k] gn += [1-a[k]+b[j] for j in range(m)] gd = [a[k]-b[j] for j in range(m,q)] gd += [1-a[k]+a[j] for j in range(n,p)] hn = [1-a[k]+b[j] for j in range(q)] hd = [1+a[j]-a[k] for j in range(p) if j != k] hz = (-ctx.one)**(q-m-n) / z**(ctx.one/r) terms.append((bases, expts, gn, gd, hn, hd, hz)) return terms return ctx.hypercomb(h, a+b, **kwargs) @defun_wrapped def appellf1(ctx,a,b1,b2,c,z1,z2,**kwargs): # Assume z1 smaller # We will use z1 for the outer loop if abs(z1) > abs(z2): z1, z2 = z2, z1 b1, b2 = b2, b1 def ok(x): return abs(x) < 0.99 # Finite cases if ctx.isnpint(a): pass elif ctx.isnpint(b1): pass elif ctx.isnpint(b2): z1, z2, b1, b2 = z2, z1, b2, b1 else: #print z1, z2 # Note: ok if |z2| > 1, because # 2F1 implements analytic continuation if not ok(z1): u1 = (z1-z2)/(z1-1) if not ok(u1): raise ValueError("Analytic continuation not implemented") #print "Using analytic continuation" return (1-z1)**(-b1)*(1-z2)**(c-a-b2)*\ ctx.appellf1(c-a,b1,c-b1-b2,c,u1,z2,**kwargs) #print "inner is", a, b2, c one = ctx.one s = 0 t = 1 k = 0 while 1: h = ctx.hyp2f1(a,b2,c,z2,zeroprec=ctx.prec,**kwargs) term = t * h if abs(term) < ctx.eps and abs(h) > 10*ctx.eps: break s += term k += 1 t = (t*a*b1*z1) / (c*k) c += one a += one b1 += one return s @defun_wrapped def coulombc(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return +_cache[l,eta][1] G3 = ctx.loggamma(2*l+2) G1 = ctx.loggamma(1+l+ctx.j*eta) G2 = ctx.loggamma(1+l-ctx.j*eta) v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3) if not (ctx.im(l) or ctx.im(eta)): v = ctx.re(v) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs): # Regular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should #ctx.prec += 10 def h(l, eta): try: jw = ctx.j*w jwz = ctx.fmul(jw, z, exact=True) jwz2 = ctx.fmul(jwz, -2, exact=True) C = ctx.coulombc(l, eta) T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \ [2*l+2], jwz2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \ (ctx.re(z) >= 0): v = ctx.re(v) return v @defun_wrapped def _coulomb_chi(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return _cache[l,eta][1] def terms(): l2 = -l-1 jeta = ctx.j*eta return [ctx.loggamma(1+l+jeta) * (-0.5j), ctx.loggamma(1+l-jeta) * (0.5j), ctx.loggamma(1+l2+jeta) * (0.5j), ctx.loggamma(1+l2-jeta) * (-0.5j), -(l+0.5)*ctx.pi] v = ctx.sum_accurately(terms, 1) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs): # Irregular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should if not ctx._im(l): l = ctx._re(l) # XXX: for isint def h(l, eta): # Force perturbation for integers and half-integers if ctx.isint(l*2): T1 = [0], [-1], [], [], [], [], 0 return (T1,) l2 = -l-1 try: chi = ctx._coulomb_chi(l, eta) jw = ctx.j*w s = ctx.sin(chi); c = ctx.cos(chi) C1 = ctx.coulombc(l,eta) C2 = ctx.coulombc(l2,eta) u = ctx.exp(jw*z) x = -2*jw*z T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \ [1+l+jw*eta], [2*l+2], x T2 = [-s, C2, z, u], [-1, 1, l2+1, 1], [], [], \ [1+l2+jw*eta], [2*l2+2], x return T1, T2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \ (ctx._re(z) >= 0): v = ctx._re(v) return v @defun def spherharm(ctx, l, m, theta, phi, **kwargs): l = ctx.convert(l) m = ctx.convert(m) theta = ctx.convert(theta) phi = ctx.convert(phi) l_isint = ctx.isint(l) l_natural = l_isint and l >= 0 m_isint = ctx.isint(m) if l_isint and l < 0 and m_isint: return ctx.spherharm(-(l+1), m, theta, phi, **kwargs) if theta == 0 and m_isint and m < 0: return ctx.zero * 1j if l_natural and m_isint: if abs(m) > l: return ctx.zero * 1j # http://functions.wolfram.com/Polynomials/ # SphericalHarmonicY/26/01/02/0004/ def h(l,m): C = [-1, ctx.expj(m*phi), (2*l+1)*ctx.fac(l+abs(m))/ctx.pi/ctx.fac(l-abs(m)), ctx.sin(theta)**2, ctx.fac(abs(m)), 2] P = [0.5*m*(ctx.sign(m)+1), 1, 0.5, 0.5*abs(m), -1, -abs(m)-1] return ((C, P, [], [], [abs(m)-l, l+abs(m)+1], [abs(m)+1], ctx.sin(0.5*theta)**2),) else: # http://functions.wolfram.com/HypergeometricFunctions/ # SphericalHarmonicYGeneral/26/01/02/0001/ def h(l,m): if ctx.isnpint(l-m+1) or ctx.isnpint(l+m+1) or ctx.isnpint(1-m): return (([0], [-1], [], [], [], [], 0),) C = [0.5*ctx.expj(m*phi), (2*l+1)/ctx.pi, ctx.gamma(l-m+1), ctx.gamma(l+m+1), ctx.cos(0.5*theta)**2, ctx.sin(0.5*theta)**2] P = [1, 0.5, 0.5, -0.5, 0.5*m, -0.5*m] return ((C, P, [], [1-m], [-l,l+1], [1-m], ctx.sin(0.5*theta)**2),) return ctx.hypercomb(h, [l,m], **kwargs)
{ "repo_name": "tovrstra/sympy", "path": "sympy/mpmath/functions/hypergeometric.py", "copies": "1", "size": "69864", "license": "bsd-3-clause", "hash": -8061213987126200000, "line_mean": 32.9145631068, "line_max": 104, "alpha_frac": 0.4586911714, "autogenerated": false, "ratio": 2.837692932575142, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8741444423512648, "avg_score": 0.01098793609249903, "num_lines": 2060 }
from functions import defun, defun_wrapped def _hermite_param(ctx, n, z, parabolic_cylinder): """ Combined calculation of the Hermite polynomial H_n(z) (and its generalization to complex n) and the parabolic cylinder function D. """ n, ntyp = ctx._convert_param(n) z = ctx.convert(z) q = -ctx.mpq_1_2 # For re(z) > 0, 2F0 -- http://functions.wolfram.com/ # HypergeometricFunctions/HermiteHGeneral/06/02/0009/ # Otherwise, there is a reflection formula # 2F0 + http://functions.wolfram.com/HypergeometricFunctions/ # HermiteHGeneral/16/01/01/0006/ # # TODO: # An alternative would be to use # http://functions.wolfram.com/HypergeometricFunctions/ # HermiteHGeneral/06/02/0006/ # # Also, the 1F1 expansion # http://functions.wolfram.com/HypergeometricFunctions/ # HermiteHGeneral/26/01/02/0001/ # should probably be used for tiny z if not z: T1 = [2, ctx.pi], [n, 0.5], [], [q*(n-1)], [], [], 0 if parabolic_cylinder: T1[1][0] += q*n return T1, can_use_2f0 = ctx.isnpint(-n) or ctx.re(z) > 0 or \ (ctx.re(z) == 0 and ctx.im(z) > 0) expprec = ctx.prec*4 + 20 if parabolic_cylinder: u = ctx.fmul(ctx.fmul(z,z,prec=expprec), -0.25, exact=True) w = ctx.fmul(z, ctx.sqrt(0.5,prec=expprec), prec=expprec) else: w = z w2 = ctx.fmul(w, w, prec=expprec) rw2 = ctx.fdiv(1, w2, prec=expprec) nrw2 = ctx.fneg(rw2, exact=True) nw = ctx.fneg(w, exact=True) if can_use_2f0: T1 = [2, w], [n, n], [], [], [q*n, q*(n-1)], [], nrw2 terms = [T1] else: T1 = [2, nw], [n, n], [], [], [q*n, q*(n-1)], [], nrw2 T2 = [2, ctx.pi, nw], [n+2, 0.5, 1], [], [q*n], [q*(n-1)], [1-q], w2 terms = [T1,T2] # Multiply by prefactor for D_n if parabolic_cylinder: expu = ctx.exp(u) for i in range(len(terms)): terms[i][1][0] += q*n terms[i][0].append(expu) terms[i][1].append(1) return tuple(terms) @defun def hermite(ctx, n, z, **kwargs): return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 0), [], **kwargs) @defun def pcfd(ctx, n, z, **kwargs): r""" Gives the parabolic cylinder function in Whittaker's notation `D_n(z) = U(-n-1/2, z)` (see :func:`~mpmath.pcfu`). It solves the differential equation .. math :: y'' + \left(n + \frac{1}{2} - \frac{1}{4} z^2\right) y = 0. and can be represented in terms of Hermite polynomials (see :func:`~mpmath.hermite`) as .. math :: D_n(z) = 2^{-n/2} e^{-z^2/4} H_n\left(\frac{z}{\sqrt{2}}\right). **Plots** .. literalinclude :: /modules/mpmath/plots/pcfd.py .. image :: /modules/mpmath/plots/pcfd.png **Examples** >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> pcfd(0,0); pcfd(1,0); pcfd(2,0); pcfd(3,0) 1.0 0.0 -1.0 0.0 >>> pcfd(4,0); pcfd(-3,0) 3.0 0.6266570686577501256039413 >>> pcfd('1/2', 2+3j) (-5.363331161232920734849056 - 3.858877821790010714163487j) >>> pcfd(2, -10) 1.374906442631438038871515e-9 Verifying the differential equation:: >>> n = mpf(2.5) >>> y = lambda z: pcfd(n,z) >>> z = 1.75 >>> chop(diff(y,z,2) + (n+0.5-0.25*z**2)*y(z)) 0.0 Rational Taylor series expansion when `n` is an integer:: >>> taylor(lambda z: pcfd(5,z), 0, 7) [0.0, 15.0, 0.0, -13.75, 0.0, 3.96875, 0.0, -0.6015625] """ return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 1), [], **kwargs) @defun def pcfu(ctx, a, z, **kwargs): r""" Gives the parabolic cylinder function `U(a,z)`, which may be defined for `\Re(z) > 0` in terms of the confluent U-function (see :func:`~mpmath.hyperu`) by .. math :: U(a,z) = 2^{-\frac{1}{4}-\frac{a}{2}} e^{-\frac{1}{4} z^2} U\left(\frac{a}{2}+\frac{1}{4}, \frac{1}{2}, \frac{1}{2}z^2\right) or, for arbitrary `z`, .. math :: e^{-\frac{1}{4}z^2} U(a,z) = U(a,0) \,_1F_1\left(-\tfrac{a}{2}+\tfrac{1}{4}; \tfrac{1}{2}; -\tfrac{1}{2}z^2\right) + U'(a,0) z \,_1F_1\left(-\tfrac{a}{2}+\tfrac{3}{4}; \tfrac{3}{2}; -\tfrac{1}{2}z^2\right). **Examples** Connection to other functions:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> z = mpf(3) >>> pcfu(0.5,z) 0.03210358129311151450551963 >>> sqrt(pi/2)*exp(z**2/4)*erfc(z/sqrt(2)) 0.03210358129311151450551963 >>> pcfu(0.5,-z) 23.75012332835297233711255 >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2)) 23.75012332835297233711255 >>> pcfu(0.5,-z) 23.75012332835297233711255 >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2)) 23.75012332835297233711255 """ n, _ = ctx._convert_param(a) return ctx.pcfd(-n-ctx.mpq_1_2, z) @defun def pcfv(ctx, a, z, **kwargs): r""" Gives the parabolic cylinder function `V(a,z)`, which can be represented in terms of :func:`~mpmath.pcfu` as .. math :: V(a,z) = \frac{\Gamma(a+\tfrac{1}{2}) (U(a,-z)-\sin(\pi a) U(a,z)}{\pi}. **Examples** Wronskian relation between `U` and `V`:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> a, z = 2, 3 >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) 0.7978845608028653558798921 >>> sqrt(2/pi) 0.7978845608028653558798921 >>> a, z = 2.5, 3 >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) 0.7978845608028653558798921 >>> a, z = 0.25, -1 >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) 0.7978845608028653558798921 >>> a, z = 2+1j, 2+3j >>> chop(pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)) 0.7978845608028653558798921 """ n, ntype = ctx._convert_param(a) z = ctx.convert(z) q = ctx.mpq_1_2 r = ctx.mpq_1_4 if ntype == 'Q' and ctx.isint(n*2): # Faster for half-integers def h(): jz = ctx.fmul(z, -1j, exact=True) T1terms = _hermite_param(ctx, -n-q, z, 1) T2terms = _hermite_param(ctx, n-q, jz, 1) for T in T1terms: T[0].append(1j) T[1].append(1) T[3].append(q-n) u = ctx.expjpi((q*n-r)) * ctx.sqrt(2/ctx.pi) for T in T2terms: T[0].append(u) T[1].append(1) return T1terms + T2terms v = ctx.hypercomb(h, [], **kwargs) if ctx._is_real_type(n) and ctx._is_real_type(z): v = ctx._re(v) return v else: def h(n): w = ctx.square_exp_arg(z, -0.25) u = ctx.square_exp_arg(z, 0.5) e = ctx.exp(w) l = [ctx.pi, q, ctx.exp(w)] Y1 = l, [-q, n*q+r, 1], [r-q*n], [], [q*n+r], [q], u Y2 = l + [z], [-q, n*q-r, 1, 1], [1-r-q*n], [], [q*n+1-r], [1+q], u c, s = ctx.cospi_sinpi(r+q*n) Y1[0].append(s) Y2[0].append(c) for Y in (Y1, Y2): Y[1].append(1) Y[3].append(q-n) return Y1, Y2 return ctx.hypercomb(h, [n], **kwargs) @defun def pcfw(ctx, a, z, **kwargs): r""" Gives the parabolic cylinder function `W(a,z)` defined in (DLMF 12.14). **Examples** Value at the origin:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> a = mpf(0.25) >>> pcfw(a,0) 0.9722833245718180765617104 >>> power(2,-0.75)*sqrt(abs(gamma(0.25+0.5j*a)/gamma(0.75+0.5j*a))) 0.9722833245718180765617104 >>> diff(pcfw,(a,0),(0,1)) -0.5142533944210078966003624 >>> -power(2,-0.25)*sqrt(abs(gamma(0.75+0.5j*a)/gamma(0.25+0.5j*a))) -0.5142533944210078966003624 """ n, _ = ctx._convert_param(a) z = ctx.convert(z) def terms(): phi2 = ctx.arg(ctx.gamma(0.5 + ctx.j*n)) phi2 = (ctx.loggamma(0.5+ctx.j*n) - ctx.loggamma(0.5-ctx.j*n))/2j rho = ctx.pi/8 + 0.5*phi2 # XXX: cancellation computing k k = ctx.sqrt(1 + ctx.exp(2*ctx.pi*n)) - ctx.exp(ctx.pi*n) C = ctx.sqrt(k/2) * ctx.exp(0.25*ctx.pi*n) yield C * ctx.expj(rho) * ctx.pcfu(ctx.j*n, z*ctx.expjpi(-0.25)) yield C * ctx.expj(-rho) * ctx.pcfu(-ctx.j*n, z*ctx.expjpi(0.25)) v = ctx.sum_accurately(terms) if ctx._is_real_type(n) and ctx._is_real_type(z): v = ctx._re(v) return v """ Even/odd PCFs. Useful? @defun def pcfy1(ctx, a, z, **kwargs): a, _ = ctx._convert_param(n) z = ctx.convert(z) def h(): w = ctx.square_exp_arg(z) w1 = ctx.fmul(w, -0.25, exact=True) w2 = ctx.fmul(w, 0.5, exact=True) e = ctx.exp(w1) return [e], [1], [], [], [ctx.mpq_1_2*a+ctx.mpq_1_4], [ctx.mpq_1_2], w2 return ctx.hypercomb(h, [], **kwargs) @defun def pcfy2(ctx, a, z, **kwargs): a, _ = ctx._convert_param(n) z = ctx.convert(z) def h(): w = ctx.square_exp_arg(z) w1 = ctx.fmul(w, -0.25, exact=True) w2 = ctx.fmul(w, 0.5, exact=True) e = ctx.exp(w1) return [e, z], [1, 1], [], [], [ctx.mpq_1_2*a+ctx.mpq_3_4], \ [ctx.mpq_3_2], w2 return ctx.hypercomb(h, [], **kwargs) """ @defun_wrapped def gegenbauer(ctx, n, a, z, **kwargs): # Special cases: a+0.5, a*2 poles if ctx.isnpint(a): return 0*(z+n) if ctx.isnpint(a+0.5): # TODO: something else is required here # E.g.: gegenbauer(-2, -0.5, 3) == -12 if ctx.isnpint(n+1): raise NotImplementedError("Gegenbauer function with two limits") def h(a): a2 = 2*a T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) return [T] return ctx.hypercomb(h, [a], **kwargs) def h(n): a2 = 2*a T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) return [T] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def jacobi(ctx, n, a, b, x, **kwargs): if not ctx.isnpint(a): def h(n): return (([], [], [a+n+1], [n+1, a+1], [-n, a+b+n+1], [a+1], (1-x)*0.5),) return ctx.hypercomb(h, [n], **kwargs) if not ctx.isint(b): def h(n, a): return (([], [], [-b], [n+1, -b-n], [-n, a+b+n+1], [b+1], (x+1)*0.5),) return ctx.hypercomb(h, [n, a], **kwargs) # XXX: determine appropriate limit return ctx.binomial(n+a,n) * ctx.hyp2f1(-n,1+n+a+b,a+1,(1-x)/2, **kwargs) @defun_wrapped def laguerre(ctx, n, a, z, **kwargs): # XXX: limits, poles #if ctx.isnpint(n): # return 0*(a+z) def h(a): return (([], [], [a+n+1], [a+1, n+1], [-n], [a+1], z),) return ctx.hypercomb(h, [a], **kwargs) @defun_wrapped def legendre(ctx, n, x, **kwargs): if ctx.isint(n): n = int(n) # Accuracy near zeros if (n + (n < 0)) & 1: if not x: return x mag = ctx.mag(x) if mag < -2*ctx.prec-10: return x if mag < -5: ctx.prec += -mag return ctx.hyp2f1(-n,n+1,1,(1-x)/2, **kwargs) @defun def legenp(ctx, n, m, z, type=2, **kwargs): # Legendre function, 1st kind n = ctx.convert(n) m = ctx.convert(m) # Faster if not m: return ctx.legendre(n, z, **kwargs) # TODO: correct evaluation at singularities if type == 2: def h(n,m): g = m*0.5 T = [1+z, 1-z], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) return (T,) return ctx.hypercomb(h, [n,m], **kwargs) if type == 3: def h(n,m): g = m*0.5 T = [z+1, z-1], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) return (T,) return ctx.hypercomb(h, [n,m], **kwargs) raise ValueError("requires type=2 or type=3") @defun def legenq(ctx, n, m, z, type=2, **kwargs): # Legendre function, 2nd kind n = ctx.convert(n) m = ctx.convert(m) z = ctx.convert(z) if z in (1, -1): #if ctx.isint(m): # return ctx.nan #return ctx.inf # unsigned return ctx.nan if type == 2: def h(n, m): cos, sin = ctx.cospi_sinpi(m) s = 2 * sin / ctx.pi c = cos a = 1+z b = 1-z u = m/2 w = (1-z)/2 T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ [-n, n+1], [1-m], w T2 = [-s, a, b], [-1, -u, u], [n+m+1], [n-m+1, m+1], \ [-n, n+1], [m+1], w return T1, T2 return ctx.hypercomb(h, [n, m], **kwargs) if type == 3: # The following is faster when there only is a single series # Note: not valid for -1 < z < 0 (?) if abs(z) > 1: def h(n, m): T1 = [ctx.expjpi(m), 2, ctx.pi, z, z-1, z+1], \ [1, -n-1, 0.5, -n-m-1, 0.5*m, 0.5*m], \ [n+m+1], [n+1.5], \ [0.5*(2+n+m), 0.5*(1+n+m)], [n+1.5], z**(-2) return [T1] return ctx.hypercomb(h, [n, m], **kwargs) else: # not valid for 1 < z < inf ? def h(n, m): s = 2 * ctx.sinpi(m) / ctx.pi c = ctx.expjpi(m) a = 1+z b = z-1 u = m/2 w = (1-z)/2 T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ [-n, n+1], [1-m], w T2 = [-s, c, a, b], [-1, 1, -u, u], [n+m+1], [n-m+1, m+1], \ [-n, n+1], [m+1], w return T1, T2 return ctx.hypercomb(h, [n, m], **kwargs) raise ValueError("requires type=2 or type=3") @defun_wrapped def chebyt(ctx, n, x, **kwargs): if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1: return x * 0 return ctx.hyp2f1(-n,n,(1,2),(1-x)/2, **kwargs) @defun_wrapped def chebyu(ctx, n, x, **kwargs): if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1: return x * 0 return (n+1) * ctx.hyp2f1(-n, n+2, (3,2), (1-x)/2, **kwargs) @defun def spherharm(ctx, l, m, theta, phi, **kwargs): l = ctx.convert(l) m = ctx.convert(m) theta = ctx.convert(theta) phi = ctx.convert(phi) l_isint = ctx.isint(l) l_natural = l_isint and l >= 0 m_isint = ctx.isint(m) if l_isint and l < 0 and m_isint: return ctx.spherharm(-(l+1), m, theta, phi, **kwargs) if theta == 0 and m_isint and m < 0: return ctx.zero * 1j if l_natural and m_isint: if abs(m) > l: return ctx.zero * 1j # http://functions.wolfram.com/Polynomials/ # SphericalHarmonicY/26/01/02/0004/ def h(l,m): absm = abs(m) C = [-1, ctx.expj(m*phi), (2*l+1)*ctx.fac(l+absm)/ctx.pi/ctx.fac(l-absm), ctx.sin(theta)**2, ctx.fac(absm), 2] P = [0.5*m*(ctx.sign(m)+1), 1, 0.5, 0.5*absm, -1, -absm-1] return ((C, P, [], [], [absm-l, l+absm+1], [absm+1], ctx.sin(0.5*theta)**2),) else: # http://functions.wolfram.com/HypergeometricFunctions/ # SphericalHarmonicYGeneral/26/01/02/0001/ def h(l,m): if ctx.isnpint(l-m+1) or ctx.isnpint(l+m+1) or ctx.isnpint(1-m): return (([0], [-1], [], [], [], [], 0),) cos, sin = ctx.cos_sin(0.5*theta) C = [0.5*ctx.expj(m*phi), (2*l+1)/ctx.pi, ctx.gamma(l-m+1), ctx.gamma(l+m+1), cos**2, sin**2] P = [1, 0.5, 0.5, -0.5, 0.5*m, -0.5*m] return ((C, P, [], [1-m], [-l,l+1], [1-m], sin**2),) return ctx.hypercomb(h, [l,m], **kwargs)
{ "repo_name": "tarballs-are-good/sympy", "path": "sympy/mpmath/functions/orthogonal.py", "copies": "2", "size": "16126", "license": "bsd-3-clause", "hash": 2767997674997057000, "line_mean": 31.7099391481, "line_max": 84, "alpha_frac": 0.4752573484, "autogenerated": false, "ratio": 2.544737257377308, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8990867821366175, "avg_score": 0.005825356882226567, "num_lines": 493 }
from .functions import defun, defun_wrapped def _hermite_param(ctx, n, z, parabolic_cylinder): """ Combined calculation of the Hermite polynomial H_n(z) (and its generalization to complex n) and the parabolic cylinder function D. """ n, ntyp = ctx._convert_param(n) z = ctx.convert(z) q = -ctx.mpq_1_2 # For re(z) > 0, 2F0 -- http://functions.wolfram.com/ # HypergeometricFunctions/HermiteHGeneral/06/02/0009/ # Otherwise, there is a reflection formula # 2F0 + http://functions.wolfram.com/HypergeometricFunctions/ # HermiteHGeneral/16/01/01/0006/ # # TODO: # An alternative would be to use # http://functions.wolfram.com/HypergeometricFunctions/ # HermiteHGeneral/06/02/0006/ # # Also, the 1F1 expansion # http://functions.wolfram.com/HypergeometricFunctions/ # HermiteHGeneral/26/01/02/0001/ # should probably be used for tiny z if not z: T1 = [2, ctx.pi], [n, 0.5], [], [q*(n-1)], [], [], 0 if parabolic_cylinder: T1[1][0] += q*n return T1, can_use_2f0 = ctx.isnpint(-n) or ctx.re(z) > 0 or \ (ctx.re(z) == 0 and ctx.im(z) > 0) expprec = ctx.prec*4 + 20 if parabolic_cylinder: u = ctx.fmul(ctx.fmul(z,z,prec=expprec), -0.25, exact=True) w = ctx.fmul(z, ctx.sqrt(0.5,prec=expprec), prec=expprec) else: w = z w2 = ctx.fmul(w, w, prec=expprec) rw2 = ctx.fdiv(1, w2, prec=expprec) nrw2 = ctx.fneg(rw2, exact=True) nw = ctx.fneg(w, exact=True) if can_use_2f0: T1 = [2, w], [n, n], [], [], [q*n, q*(n-1)], [], nrw2 terms = [T1] else: T1 = [2, nw], [n, n], [], [], [q*n, q*(n-1)], [], nrw2 T2 = [2, ctx.pi, nw], [n+2, 0.5, 1], [], [q*n], [q*(n-1)], [1-q], w2 terms = [T1,T2] # Multiply by prefactor for D_n if parabolic_cylinder: expu = ctx.exp(u) for i in range(len(terms)): terms[i][1][0] += q*n terms[i][0].append(expu) terms[i][1].append(1) return tuple(terms) @defun def hermite(ctx, n, z, **kwargs): return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 0), [], **kwargs) @defun def pcfd(ctx, n, z, **kwargs): r""" Gives the parabolic cylinder function in Whittaker's notation `D_n(z) = U(-n-1/2, z)` (see :func:`~mpmath.pcfu`). It solves the differential equation .. math :: y'' + \left(n + \frac{1}{2} - \frac{1}{4} z^2\right) y = 0. and can be represented in terms of Hermite polynomials (see :func:`~mpmath.hermite`) as .. math :: D_n(z) = 2^{-n/2} e^{-z^2/4} H_n\left(\frac{z}{\sqrt{2}}\right). **Plots** .. literalinclude :: /modules/mpmath/plots/pcfd.py .. image :: /modules/mpmath/plots/pcfd.png **Examples** >>> from sympy.mpmath import * >>> mp.dps = 25; mp.pretty = True >>> pcfd(0,0); pcfd(1,0); pcfd(2,0); pcfd(3,0) 1.0 0.0 -1.0 0.0 >>> pcfd(4,0); pcfd(-3,0) 3.0 0.6266570686577501256039413 >>> pcfd('1/2', 2+3j) (-5.363331161232920734849056 - 3.858877821790010714163487j) >>> pcfd(2, -10) 1.374906442631438038871515e-9 Verifying the differential equation:: >>> n = mpf(2.5) >>> y = lambda z: pcfd(n,z) >>> z = 1.75 >>> chop(diff(y,z,2) + (n+0.5-0.25*z**2)*y(z)) 0.0 Rational Taylor series expansion when `n` is an integer:: >>> taylor(lambda z: pcfd(5,z), 0, 7) [0.0, 15.0, 0.0, -13.75, 0.0, 3.96875, 0.0, -0.6015625] """ return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 1), [], **kwargs) @defun def pcfu(ctx, a, z, **kwargs): r""" Gives the parabolic cylinder function `U(a,z)`, which may be defined for `\Re(z) > 0` in terms of the confluent U-function (see :func:`~mpmath.hyperu`) by .. math :: U(a,z) = 2^{-\frac{1}{4}-\frac{a}{2}} e^{-\frac{1}{4} z^2} U\left(\frac{a}{2}+\frac{1}{4}, \frac{1}{2}, \frac{1}{2}z^2\right) or, for arbitrary `z`, .. math :: e^{-\frac{1}{4}z^2} U(a,z) = U(a,0) \,_1F_1\left(-\tfrac{a}{2}+\tfrac{1}{4}; \tfrac{1}{2}; -\tfrac{1}{2}z^2\right) + U'(a,0) z \,_1F_1\left(-\tfrac{a}{2}+\tfrac{3}{4}; \tfrac{3}{2}; -\tfrac{1}{2}z^2\right). **Examples** Connection to other functions:: >>> from sympy.mpmath import * >>> mp.dps = 25; mp.pretty = True >>> z = mpf(3) >>> pcfu(0.5,z) 0.03210358129311151450551963 >>> sqrt(pi/2)*exp(z**2/4)*erfc(z/sqrt(2)) 0.03210358129311151450551963 >>> pcfu(0.5,-z) 23.75012332835297233711255 >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2)) 23.75012332835297233711255 >>> pcfu(0.5,-z) 23.75012332835297233711255 >>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2)) 23.75012332835297233711255 """ n, _ = ctx._convert_param(a) return ctx.pcfd(-n-ctx.mpq_1_2, z) @defun def pcfv(ctx, a, z, **kwargs): r""" Gives the parabolic cylinder function `V(a,z)`, which can be represented in terms of :func:`~mpmath.pcfu` as .. math :: V(a,z) = \frac{\Gamma(a+\tfrac{1}{2}) (U(a,-z)-\sin(\pi a) U(a,z)}{\pi}. **Examples** Wronskian relation between `U` and `V`:: >>> from sympy.mpmath import * >>> mp.dps = 25; mp.pretty = True >>> a, z = 2, 3 >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) 0.7978845608028653558798921 >>> sqrt(2/pi) 0.7978845608028653558798921 >>> a, z = 2.5, 3 >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) 0.7978845608028653558798921 >>> a, z = 0.25, -1 >>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z) 0.7978845608028653558798921 >>> a, z = 2+1j, 2+3j >>> chop(pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)) 0.7978845608028653558798921 """ n, ntype = ctx._convert_param(a) z = ctx.convert(z) q = ctx.mpq_1_2 r = ctx.mpq_1_4 if ntype == 'Q' and ctx.isint(n*2): # Faster for half-integers def h(): jz = ctx.fmul(z, -1j, exact=True) T1terms = _hermite_param(ctx, -n-q, z, 1) T2terms = _hermite_param(ctx, n-q, jz, 1) for T in T1terms: T[0].append(1j) T[1].append(1) T[3].append(q-n) u = ctx.expjpi((q*n-r)) * ctx.sqrt(2/ctx.pi) for T in T2terms: T[0].append(u) T[1].append(1) return T1terms + T2terms v = ctx.hypercomb(h, [], **kwargs) if ctx._is_real_type(n) and ctx._is_real_type(z): v = ctx._re(v) return v else: def h(n): w = ctx.square_exp_arg(z, -0.25) u = ctx.square_exp_arg(z, 0.5) e = ctx.exp(w) l = [ctx.pi, q, ctx.exp(w)] Y1 = l, [-q, n*q+r, 1], [r-q*n], [], [q*n+r], [q], u Y2 = l + [z], [-q, n*q-r, 1, 1], [1-r-q*n], [], [q*n+1-r], [1+q], u c, s = ctx.cospi_sinpi(r+q*n) Y1[0].append(s) Y2[0].append(c) for Y in (Y1, Y2): Y[1].append(1) Y[3].append(q-n) return Y1, Y2 return ctx.hypercomb(h, [n], **kwargs) @defun def pcfw(ctx, a, z, **kwargs): r""" Gives the parabolic cylinder function `W(a,z)` defined in (DLMF 12.14). **Examples** Value at the origin:: >>> from sympy.mpmath import * >>> mp.dps = 25; mp.pretty = True >>> a = mpf(0.25) >>> pcfw(a,0) 0.9722833245718180765617104 >>> power(2,-0.75)*sqrt(abs(gamma(0.25+0.5j*a)/gamma(0.75+0.5j*a))) 0.9722833245718180765617104 >>> diff(pcfw,(a,0),(0,1)) -0.5142533944210078966003624 >>> -power(2,-0.25)*sqrt(abs(gamma(0.75+0.5j*a)/gamma(0.25+0.5j*a))) -0.5142533944210078966003624 """ n, _ = ctx._convert_param(a) z = ctx.convert(z) def terms(): phi2 = ctx.arg(ctx.gamma(0.5 + ctx.j*n)) phi2 = (ctx.loggamma(0.5+ctx.j*n) - ctx.loggamma(0.5-ctx.j*n))/2j rho = ctx.pi/8 + 0.5*phi2 # XXX: cancellation computing k k = ctx.sqrt(1 + ctx.exp(2*ctx.pi*n)) - ctx.exp(ctx.pi*n) C = ctx.sqrt(k/2) * ctx.exp(0.25*ctx.pi*n) yield C * ctx.expj(rho) * ctx.pcfu(ctx.j*n, z*ctx.expjpi(-0.25)) yield C * ctx.expj(-rho) * ctx.pcfu(-ctx.j*n, z*ctx.expjpi(0.25)) v = ctx.sum_accurately(terms) if ctx._is_real_type(n) and ctx._is_real_type(z): v = ctx._re(v) return v """ Even/odd PCFs. Useful? @defun def pcfy1(ctx, a, z, **kwargs): a, _ = ctx._convert_param(n) z = ctx.convert(z) def h(): w = ctx.square_exp_arg(z) w1 = ctx.fmul(w, -0.25, exact=True) w2 = ctx.fmul(w, 0.5, exact=True) e = ctx.exp(w1) return [e], [1], [], [], [ctx.mpq_1_2*a+ctx.mpq_1_4], [ctx.mpq_1_2], w2 return ctx.hypercomb(h, [], **kwargs) @defun def pcfy2(ctx, a, z, **kwargs): a, _ = ctx._convert_param(n) z = ctx.convert(z) def h(): w = ctx.square_exp_arg(z) w1 = ctx.fmul(w, -0.25, exact=True) w2 = ctx.fmul(w, 0.5, exact=True) e = ctx.exp(w1) return [e, z], [1, 1], [], [], [ctx.mpq_1_2*a+ctx.mpq_3_4], \ [ctx.mpq_3_2], w2 return ctx.hypercomb(h, [], **kwargs) """ @defun_wrapped def gegenbauer(ctx, n, a, z, **kwargs): # Special cases: a+0.5, a*2 poles if ctx.isnpint(a): return 0*(z+n) if ctx.isnpint(a+0.5): # TODO: something else is required here # E.g.: gegenbauer(-2, -0.5, 3) == -12 if ctx.isnpint(n+1): raise NotImplementedError("Gegenbauer function with two limits") def h(a): a2 = 2*a T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) return [T] return ctx.hypercomb(h, [a], **kwargs) def h(n): a2 = 2*a T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z) return [T] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def jacobi(ctx, n, a, b, x, **kwargs): if not ctx.isnpint(a): def h(n): return (([], [], [a+n+1], [n+1, a+1], [-n, a+b+n+1], [a+1], (1-x)*0.5),) return ctx.hypercomb(h, [n], **kwargs) if not ctx.isint(b): def h(n, a): return (([], [], [-b], [n+1, -b-n], [-n, a+b+n+1], [b+1], (x+1)*0.5),) return ctx.hypercomb(h, [n, a], **kwargs) # XXX: determine appropriate limit return ctx.binomial(n+a,n) * ctx.hyp2f1(-n,1+n+a+b,a+1,(1-x)/2, **kwargs) @defun_wrapped def laguerre(ctx, n, a, z, **kwargs): # XXX: limits, poles #if ctx.isnpint(n): # return 0*(a+z) def h(a): return (([], [], [a+n+1], [a+1, n+1], [-n], [a+1], z),) return ctx.hypercomb(h, [a], **kwargs) @defun_wrapped def legendre(ctx, n, x, **kwargs): if ctx.isint(n): n = int(n) # Accuracy near zeros if (n + (n < 0)) & 1: if not x: return x mag = ctx.mag(x) if mag < -2*ctx.prec-10: return x if mag < -5: ctx.prec += -mag return ctx.hyp2f1(-n,n+1,1,(1-x)/2, **kwargs) @defun def legenp(ctx, n, m, z, type=2, **kwargs): # Legendre function, 1st kind n = ctx.convert(n) m = ctx.convert(m) # Faster if not m: return ctx.legendre(n, z, **kwargs) # TODO: correct evaluation at singularities if type == 2: def h(n,m): g = m*0.5 T = [1+z, 1-z], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) return (T,) return ctx.hypercomb(h, [n,m], **kwargs) if type == 3: def h(n,m): g = m*0.5 T = [z+1, z-1], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z) return (T,) return ctx.hypercomb(h, [n,m], **kwargs) raise ValueError("requires type=2 or type=3") @defun def legenq(ctx, n, m, z, type=2, **kwargs): # Legendre function, 2nd kind n = ctx.convert(n) m = ctx.convert(m) z = ctx.convert(z) if z in (1, -1): #if ctx.isint(m): # return ctx.nan #return ctx.inf # unsigned return ctx.nan if type == 2: def h(n, m): cos, sin = ctx.cospi_sinpi(m) s = 2 * sin / ctx.pi c = cos a = 1+z b = 1-z u = m/2 w = (1-z)/2 T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ [-n, n+1], [1-m], w T2 = [-s, a, b], [-1, -u, u], [n+m+1], [n-m+1, m+1], \ [-n, n+1], [m+1], w return T1, T2 return ctx.hypercomb(h, [n, m], **kwargs) if type == 3: # The following is faster when there only is a single series # Note: not valid for -1 < z < 0 (?) if abs(z) > 1: def h(n, m): T1 = [ctx.expjpi(m), 2, ctx.pi, z, z-1, z+1], \ [1, -n-1, 0.5, -n-m-1, 0.5*m, 0.5*m], \ [n+m+1], [n+1.5], \ [0.5*(2+n+m), 0.5*(1+n+m)], [n+1.5], z**(-2) return [T1] return ctx.hypercomb(h, [n, m], **kwargs) else: # not valid for 1 < z < inf ? def h(n, m): s = 2 * ctx.sinpi(m) / ctx.pi c = ctx.expjpi(m) a = 1+z b = z-1 u = m/2 w = (1-z)/2 T1 = [s, c, a, b], [-1, 1, u, -u], [], [1-m], \ [-n, n+1], [1-m], w T2 = [-s, c, a, b], [-1, 1, -u, u], [n+m+1], [n-m+1, m+1], \ [-n, n+1], [m+1], w return T1, T2 return ctx.hypercomb(h, [n, m], **kwargs) raise ValueError("requires type=2 or type=3") @defun_wrapped def chebyt(ctx, n, x, **kwargs): if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1: return x * 0 return ctx.hyp2f1(-n,n,(1,2),(1-x)/2, **kwargs) @defun_wrapped def chebyu(ctx, n, x, **kwargs): if (not x) and ctx.isint(n) and int(ctx._re(n)) % 2 == 1: return x * 0 return (n+1) * ctx.hyp2f1(-n, n+2, (3,2), (1-x)/2, **kwargs) @defun def spherharm(ctx, l, m, theta, phi, **kwargs): l = ctx.convert(l) m = ctx.convert(m) theta = ctx.convert(theta) phi = ctx.convert(phi) l_isint = ctx.isint(l) l_natural = l_isint and l >= 0 m_isint = ctx.isint(m) if l_isint and l < 0 and m_isint: return ctx.spherharm(-(l+1), m, theta, phi, **kwargs) if theta == 0 and m_isint and m < 0: return ctx.zero * 1j if l_natural and m_isint: if abs(m) > l: return ctx.zero * 1j # http://functions.wolfram.com/Polynomials/ # SphericalHarmonicY/26/01/02/0004/ def h(l,m): absm = abs(m) C = [-1, ctx.expj(m*phi), (2*l+1)*ctx.fac(l+absm)/ctx.pi/ctx.fac(l-absm), ctx.sin(theta)**2, ctx.fac(absm), 2] P = [0.5*m*(ctx.sign(m)+1), 1, 0.5, 0.5*absm, -1, -absm-1] return ((C, P, [], [], [absm-l, l+absm+1], [absm+1], ctx.sin(0.5*theta)**2),) else: # http://functions.wolfram.com/HypergeometricFunctions/ # SphericalHarmonicYGeneral/26/01/02/0001/ def h(l,m): if ctx.isnpint(l-m+1) or ctx.isnpint(l+m+1) or ctx.isnpint(1-m): return (([0], [-1], [], [], [], [], 0),) cos, sin = ctx.cos_sin(0.5*theta) C = [0.5*ctx.expj(m*phi), (2*l+1)/ctx.pi, ctx.gamma(l-m+1), ctx.gamma(l+m+1), cos**2, sin**2] P = [1, 0.5, 0.5, -0.5, 0.5*m, -0.5*m] return ((C, P, [], [1-m], [-l,l+1], [1-m], sin**2),) return ctx.hypercomb(h, [l,m], **kwargs)
{ "repo_name": "maryklayne/Funcao", "path": "sympy/mpmath/functions/orthogonal.py", "copies": "18", "size": "16151", "license": "bsd-3-clause", "hash": 2199199174172050400, "line_mean": 31.7606490872, "line_max": 84, "alpha_frac": 0.4757600149, "autogenerated": false, "ratio": 2.5450677592184054, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.005825356882226567, "num_lines": 493 }
from functions import defun, defun_wrapped @defun def gammaprod(ctx, a, b, _infsign=False): a = [ctx.convert(x) for x in a] b = [ctx.convert(x) for x in b] poles_num = [] poles_den = [] regular_num = [] regular_den = [] for x in a: [regular_num, poles_num][ctx.isnpint(x)].append(x) for x in b: [regular_den, poles_den][ctx.isnpint(x)].append(x) # One more pole in numerator or denominator gives 0 or inf if len(poles_num) < len(poles_den): return ctx.zero if len(poles_num) > len(poles_den): # Get correct sign of infinity for x+h, h -> 0 from above # XXX: hack, this should be done properly if _infsign: a = [x and x*(1+ctx.eps) or x+ctx.eps for x in poles_num] b = [x and x*(1+ctx.eps) or x+ctx.eps for x in poles_den] return ctx.sign(ctx.gammaprod(a+regular_num,b+regular_den)) * ctx.inf else: return ctx.inf # All poles cancel # lim G(i)/G(j) = (-1)**(i+j) * gamma(1-j) / gamma(1-i) p = ctx.one orig = ctx.prec try: ctx.prec = orig + 15 while poles_num: i = poles_num.pop() j = poles_den.pop() p *= (-1)**(i+j) * ctx.gamma(1-j) / ctx.gamma(1-i) for x in regular_num: p *= ctx.gamma(x) for x in regular_den: p /= ctx.gamma(x) finally: ctx.prec = orig return +p @defun def beta(ctx, x, y): x = ctx.convert(x) y = ctx.convert(y) if ctx.isinf(y): x, y = y, x if ctx.isinf(x): if x == ctx.inf and not ctx._im(y): if y == ctx.ninf: return ctx.nan if y > 0: return ctx.zero if ctx.isint(y): return ctx.nan if y < 0: return ctx.sign(ctx.gamma(y)) * ctx.inf return ctx.nan return ctx.gammaprod([x, y], [x+y]) @defun def binomial(ctx, n, k): return ctx.gammaprod([n+1], [k+1, n-k+1]) @defun def rf(ctx, x, n): return ctx.gammaprod([x+n], [x]) @defun def ff(ctx, x, n): return ctx.gammaprod([x+1], [x-n+1]) @defun_wrapped def fac2(ctx, x): if ctx.isinf(x): if x == ctx.inf: return x return ctx.nan return 2**(x/2)*(ctx.pi/2)**((ctx.cospi(x)-1)/4)*ctx.gamma(x/2+1) @defun_wrapped def barnesg(ctx, z): if ctx.isinf(z): if z == ctx.inf: return z return ctx.nan if ctx.isnan(z): return z if (not ctx._im(z)) and ctx._re(z) <= 0 and ctx.isint(ctx._re(z)): return z*0 # Account for size (would not be needed if computing log(G)) if abs(z) > 5: ctx.dps += 2*ctx.log(abs(z),2) # Reflection formula if ctx.re(z) < -ctx.dps: w = 1-z pi2 = 2*ctx.pi u = ctx.expjpi(2*w) v = ctx.j*ctx.pi/12 - ctx.j*ctx.pi*w**2/2 + w*ctx.ln(1-u) - \ ctx.j*ctx.polylog(2, u)/pi2 v = ctx.barnesg(2-z)*ctx.exp(v)/pi2**w if ctx._is_real_type(z): v = ctx._re(v) return v # Estimate terms for asymptotic expansion # TODO: fixme, obviously N = ctx.dps // 2 + 5 G = 1 while abs(z) < N or ctx.re(z) < 1: G /= ctx.gamma(z) z += 1 z -= 1 s = ctx.mpf(1)/12 s -= ctx.log(ctx.glaisher) s += z*ctx.log(2*ctx.pi)/2 s += (z**2/2-ctx.mpf(1)/12)*ctx.log(z) s -= 3*z**2/4 z2k = z2 = z**2 for k in xrange(1, N+1): t = ctx.bernoulli(2*k+2) / (4*k*(k+1)*z2k) if abs(t) < ctx.eps: #print k, N # check how many terms were needed break z2k *= z2 s += t #if k == N: # print "warning: series for barnesg failed to converge", ctx.dps return G*ctx.exp(s) @defun def superfac(ctx, z): return ctx.barnesg(z+2) @defun_wrapped def hyperfac(ctx, z): # XXX: estimate needed extra bits accurately if z == ctx.inf: return z if abs(z) > 5: extra = 4*int(ctx.log(abs(z),2)) else: extra = 0 ctx.prec += extra if not ctx._im(z) and ctx._re(z) < 0 and ctx.isint(ctx._re(z)): n = int(ctx.re(z)) h = ctx.hyperfac(-n-1) if ((n+1)//2) & 1: h = -h if ctx._is_complex_type(z): return h + 0j return h zp1 = z+1 # Wrong branch cut #v = ctx.gamma(zp1)**z #ctx.prec -= extra #return v / ctx.barnesg(zp1) v = ctx.exp(z*ctx.loggamma(zp1)) ctx.prec -= extra return v / ctx.barnesg(zp1) @defun_wrapped def loggamma_old(ctx, z): a = ctx._re(z) b = ctx._im(z) if not b and a > 0: return ctx.ln(ctx.gamma_old(z)) u = ctx.arg(z) w = ctx.ln(ctx.gamma_old(z)) if b: gi = -b - u/2 + a*u + b*ctx.ln(abs(z)) n = ctx.floor((gi-ctx._im(w))/(2*ctx.pi)+0.5) * (2*ctx.pi) return w + n*ctx.j elif a < 0: n = int(ctx.floor(a)) w += (n-(n%2))*ctx.pi*ctx.j return w ''' @defun def psi0(ctx, z): """Shortcut for psi(0,z) (the digamma function)""" return ctx.psi(0, z) @defun def psi1(ctx, z): """Shortcut for psi(1,z) (the trigamma function)""" return ctx.psi(1, z) @defun def psi2(ctx, z): """Shortcut for psi(2,z) (the tetragamma function)""" return ctx.psi(2, z) @defun def psi3(ctx, z): """Shortcut for psi(3,z) (the pentagamma function)""" return ctx.psi(3, z) '''
{ "repo_name": "tarballs-are-good/sympy", "path": "sympy/mpmath/functions/factorials.py", "copies": "3", "size": "5368", "license": "bsd-3-clause", "hash": 6028471188974831000, "line_mean": 26.387755102, "line_max": 81, "alpha_frac": 0.5134128167, "autogenerated": false, "ratio": 2.6693187468920936, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46827315635920935, "avg_score": null, "num_lines": null }
from .functions import defun, defun_wrapped @defun def j0(ctx, x): """Computes the Bessel function `J_0(x)`. See :func:`~mpmath.besselj`.""" return ctx.besselj(0, x) @defun def j1(ctx, x): """Computes the Bessel function `J_1(x)`. See :func:`~mpmath.besselj`.""" return ctx.besselj(1, x) @defun def besselj(ctx, n, z, derivative=0, **kwargs): if type(n) is int: n_isint = True else: n = ctx.convert(n) n_isint = ctx.isint(n) if n_isint: n = int(ctx._re(n)) if n_isint and n < 0: return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs) z = ctx.convert(z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) # TODO: the integer special-casing shouldn't be necessary. # However, the hypergeometric series gets inaccurate for large d # because of inaccurate pole cancellation at a pole far from # zero (needs to be fixed in hypercomb or hypsum) if ctx.isint(d) and d >= 0: d = int(d) orig = ctx.prec try: ctx.prec += 15 v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z) for k in range(d+1)) finally: ctx.prec = orig v *= ctx.mpf(2)**(-d) else: def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2)] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20: try: return ctx._besselj(n, z) except NotImplementedError: pass if not z: if not n: v = ctx.one + n+z elif ctx.re(n) > 0: v = n*z else: v = ctx.inf + z + n else: #v = 0 orig = ctx.prec try: # XXX: workaround for accuracy in low level hypergeometric series # when alternating, large arguments ctx.prec += min(3*abs(M), ctx.prec) w = ctx.fmul(z, 0.5, exact=True) def h(n): r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) finally: ctx.prec = orig v = +v return v @defun def besseli(ctx, n, z, derivative=0, **kwargs): n = ctx.convert(n) z = ctx.convert(z) if not z: if derivative: raise ValueError if not n: # I(0,0) = 1 return 1+n+z if ctx.isint(n): return 0*(n+z) r = ctx.re(n) if r == 0: return ctx.nan*(n+z) elif r > 0: return 0*(n+z) else: return ctx.inf+(n+z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2), n+1] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: def h(n): w = ctx.fmul(z, 0.5, exact=True) r = ctx.fmul(w, w, prec=max(0,ctx.prec+M)) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) return v @defun_wrapped def bessely(ctx, n, z, derivative=0, **kwargs): if not z: if derivative: # Not implemented raise ValueError if not n: # ~ log(z/2) return -ctx.inf + (n+z) if ctx.im(n): return ctx.nan * (n+z) r = ctx.re(n) q = n+0.5 if ctx.isint(q): if n > 0: return -ctx.inf + (n+z) else: return 0 * (n+z) if r < 0 and int(ctx.floor(q)) % 2: return ctx.inf + (n+z) else: return ctx.ninf + (n+z) # XXX: use hypercomb ctx.prec += 10 m, d = ctx.nint_distance(n) if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 n += h elif d < 0: ctx.prec -= d # TODO: avoid cancellation for imaginary arguments cos, sin = ctx.cospi_sinpi(n) return (ctx.besselj(n,z,derivative,**kwargs)*cos - \ ctx.besselj(-n,z,derivative,**kwargs))/sin @defun_wrapped def besselk(ctx, n, z, **kwargs): if not z: return ctx.inf M = ctx.mag(z) if M < 1: # Represent as limit definition def h(n): r = (z/2)**2 T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r return T1, T2 # We could use the limit definition always, but it leads # to very bad cancellation (of exponentially large terms) # for large real z # Instead represent in terms of 2F0 else: ctx.prec += M def h(n): return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \ [n+0.5, 0.5-n], [], -1/(2*z))] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def hankel1(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def hankel2(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def whitm(ctx,k,m,z,**kwargs): if z == 0: # M(k,m,z) = 0^(1/2+m) if ctx.re(m) > -0.5: return z elif ctx.re(m) < -0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs) @defun_wrapped def whitw(ctx,k,m,z,**kwargs): if z == 0: g = abs(ctx.re(m)) if g < 0.5: return z elif g > 0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs) @defun def hyperu(ctx, a, b, z, **kwargs): a, atype = ctx._convert_param(a) b, btype = ctx._convert_param(b) z = ctx.convert(z) if not z: if ctx.re(b) <= 1: return ctx.gammaprod([1-b],[a-b+1]) else: return ctx.inf + z bb = 1+a-b bb, bbtype = ctx._convert_param(bb) try: orig = ctx.prec try: ctx.prec += 10 v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec) return v / z**a finally: ctx.prec = orig except ctx.NoConvergence: pass def h(a,b): w = ctx.sinpi(b) T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z) T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z) return T1, T2 return ctx.hypercomb(h, [a,b], **kwargs) @defun def struveh(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) @defun def struvel(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) def _anger(ctx,which,v,z,**kwargs): v = ctx._convert_param(v)[0] z = ctx.convert(z) def h(v): b = ctx.mpq_1_2 u = v*b m = b*3 a1,a2,b1,b2 = m-u, m+u, 1-u, 1+u c, s = ctx.cospi_sinpi(u) if which == 0: A, B = [b*z, s], [c] if which == 1: A, B = [b*z, -c], [s] w = ctx.square_exp_arg(z, mult=-0.25) T1 = A, [1, 1], [], [a1,a2], [1], [a1,a2], w T2 = B, [1], [], [b1,b2], [1], [b1,b2], w return T1, T2 return ctx.hypercomb(h, [v], **kwargs) @defun def angerj(ctx, v, z, **kwargs): return _anger(ctx, 0, v, z, **kwargs) @defun def webere(ctx, v, z, **kwargs): return _anger(ctx, 1, v, z, **kwargs) @defun def lommels1(ctx, u, v, z, **kwargs): u = ctx._convert_param(u)[0] v = ctx._convert_param(v)[0] z = ctx.convert(z) def h(u,v): b = ctx.mpq_1_2 w = ctx.square_exp_arg(z, mult=-0.25) return ([u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], \ [b*(u-v+3),b*(u+v+3)], w), return ctx.hypercomb(h, [u,v], **kwargs) @defun def lommels2(ctx, u, v, z, **kwargs): u = ctx._convert_param(u)[0] v = ctx._convert_param(v)[0] z = ctx.convert(z) # Asymptotic expansion (GR p. 947) -- need to be careful # not to use for small arguments # def h(u,v): # b = ctx.mpq_1_2 # w = -(z/2)**(-2) # return ([z], [u-1], [], [], [b*(1-u+v)], [b*(1-u-v)], w), def h(u,v): b = ctx.mpq_1_2 w = ctx.square_exp_arg(z, mult=-0.25) T1 = [u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], [b*(u-v+3),b*(u+v+3)], w T2 = [2, z], [u+v-1, -v], [v, b*(u+v+1)], [b*(v-u+1)], [], [1-v], w T3 = [2, z], [u-v-1, v], [-v, b*(u-v+1)], [b*(1-u-v)], [], [1+v], w #c1 = ctx.cospi((u-v)*b) #c2 = ctx.cospi((u+v)*b) #s = ctx.sinpi(v) #r1 = (u-v+1)*b #r2 = (u+v+1)*b #T2 = [c1, s, z, 2], [1, -1, -v, v], [], [-v+1], [], [-v+1], w #T3 = [-c2, s, z, 2], [1, -1, v, -v], [], [v+1], [], [v+1], w #T2 = [c1, s, z, 2], [1, -1, -v, v+u-1], [r1, r2], [-v+1], [], [-v+1], w #T3 = [-c2, s, z, 2], [1, -1, v, -v+u-1], [r1, r2], [v+1], [], [v+1], w return T1, T2, T3 return ctx.hypercomb(h, [u,v], **kwargs) @defun def ber(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos, sin = ctx.cospi_sinpi(-0.75*n) T1 = [cos, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r T2 = [sin, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def bei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos, sin = ctx.cospi_sinpi(0.75*n) T1 = [cos, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r T2 = [sin, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def ker(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos1, sin1 = ctx.cospi_sinpi(0.25*n) cos2, sin2 = ctx.cospi_sinpi(0.75*n) T1 = [2, z, 4*cos1], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r T2 = [2, z, -sin1], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r T3 = [2, z, 4*cos2], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T4 = [2, z, -sin2], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) @defun def kei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos1, sin1 = ctx.cospi_sinpi(0.75*n) cos2, sin2 = ctx.cospi_sinpi(0.25*n) T1 = [-cos1, 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r T2 = [-sin1, 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T3 = [-sin2, 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r T4 = [-cos2, 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) # TODO: do this more generically? def c_memo(f): name = f.__name__ def f_wrapped(ctx): cache = ctx._misc_const_cache prec = ctx.prec p,v = cache.get(name, (-1,0)) if p >= prec: return +v else: cache[name] = (prec, f(ctx)) return cache[name][1] return f_wrapped @c_memo def _airyai_C1(ctx): return 1 / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3)) @c_memo def _airyai_C2(ctx): return -1 / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3)) @c_memo def _airybi_C1(ctx): return 1 / (ctx.nthroot(3,6) * ctx.gamma(ctx.mpf(2)/3)) @c_memo def _airybi_C2(ctx): return ctx.nthroot(3,6) / ctx.gamma(ctx.mpf(1)/3) def _airybi_n2_inf(ctx): prec = ctx.prec try: v = ctx.power(3,'2/3')*ctx.gamma('2/3')/(2*ctx.pi) finally: ctx.prec = prec return +v # Derivatives at z = 0 # TODO: could be expressed more elegantly using triple factorials def _airyderiv_0(ctx, z, n, ntype, which): if ntype == 'Z': if n < 0: return z r = ctx.mpq_1_3 prec = ctx.prec try: ctx.prec += 10 v = ctx.gamma((n+1)*r) * ctx.power(3,n*r) / ctx.pi if which == 0: v *= ctx.sinpi(2*(n+1)*r) v /= ctx.power(3,'2/3') else: v *= abs(ctx.sinpi(2*(n+1)*r)) v /= ctx.power(3,'1/6') finally: ctx.prec = prec return +v + z else: # singular (does the limit exist?) raise NotImplementedError @defun def airyai(ctx, z, derivative=0, **kwargs): z = ctx.convert(z) if derivative: n, ntype = ctx._convert_param(derivative) else: n = 0 # Values at infinities if not ctx.isnormal(z) and z: if n and ntype == 'Z': if n == -1: if z == ctx.inf: return ctx.mpf(1)/3 + 1/z if z == ctx.ninf: return ctx.mpf(-2)/3 + 1/z if n < -1: if z == ctx.inf: return z if z == ctx.ninf: return (-1)**n * (-z) if (not n) and z == ctx.inf or z == ctx.ninf: return 1/z # TODO: limits raise ValueError("essential singularity of Ai(z)") # Account for exponential scaling if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if n: if n == 1: def h(): # http://functions.wolfram.com/03.07.06.0005.01 if ctx._re(z) > 4: ctx.prec += extraprec w = z**1.5; r = -0.75/w; u = -2*w/3 ctx.prec -= extraprec C = -ctx.exp(u)/(2*ctx.sqrt(ctx.pi))*ctx.nthroot(z,4) return ([C],[1],[],[],[(-1,6),(7,6)],[],r), # http://functions.wolfram.com/03.07.26.0001.01 else: ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airyai_C1(ctx) * 0.5 C2 = _airyai_C2(ctx) T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) else: if z == 0: return _airyderiv_0(ctx, z, n, ntype, 0) # http://functions.wolfram.com/03.05.20.0004.01 def h(n): ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 T1 = [3, z], [n-q23, -n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 T2 = [3, z, -z], [n-q43, -n, 1], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w return T1, T2 v = ctx.hypercomb(h, [n], **kwargs) if ctx._is_real_type(z) and ctx.isint(n): v = ctx._re(v) return v else: def h(): if ctx._re(z) > 4: # We could use 1F1, but it results in huge cancellation; # the following expansion is better. # TODO: asymptotic series for derivatives ctx.prec += extraprec w = z**1.5; r = -0.75/w; u = -2*w/3 ctx.prec -= extraprec C = ctx.exp(u)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4)) return ([C],[1],[],[],[(1,6),(5,6)],[],r), else: ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airyai_C1(ctx) C2 = _airyai_C2(ctx) T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) @defun def airybi(ctx, z, derivative=0, **kwargs): z = ctx.convert(z) if derivative: n, ntype = ctx._convert_param(derivative) else: n = 0 # Values at infinities if not ctx.isnormal(z) and z: if n and ntype == 'Z': if z == ctx.inf: return z if z == ctx.ninf: if n == -1: return 1/z if n == -2: return _airybi_n2_inf(ctx) if n < -2: return (-1)**n * (-z) if not n: if z == ctx.inf: return z if z == ctx.ninf: return 1/z # TODO: limits raise ValueError("essential singularity of Bi(z)") if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if n: if n == 1: # http://functions.wolfram.com/03.08.26.0001.01 def h(): ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airybi_C1(ctx)*0.5 C2 = _airybi_C2(ctx) T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) else: if z == 0: return _airyderiv_0(ctx, z, n, ntype, 1) def h(n): ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 q16 = ctx.mpq_1_6 q56 = ctx.mpq_5_6 a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 T1 = [3, z], [n-q16, -n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 T2 = [3, z], [n-q56, 1-n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w return T1, T2 v = ctx.hypercomb(h, [n], **kwargs) if ctx._is_real_type(z) and ctx.isint(n): v = ctx._re(v) return v else: def h(): ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airybi_C1(ctx) C2 = _airybi_C2(ctx) T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) def _airy_zero(ctx, which, k, derivative, complex=False): # Asymptotic formulas are given in DLMF section 9.9 def U(t): return t**(2/3.)*(1-7/(t**2*48)) def T(t): return t**(2/3.)*(1+5/(t**2*48)) k = int(k) if k < 1: raise ValueError("k cannot be less than 1") if not derivative in (0,1): raise ValueError("Derivative should lie between 0 and 1") if which == 0: if derivative: return ctx.findroot(lambda z: ctx.airyai(z,1), -U(3*ctx.pi*(4*k-3)/8)) return ctx.findroot(ctx.airyai, -T(3*ctx.pi*(4*k-1)/8)) if which == 1 and complex == False: if derivative: return ctx.findroot(lambda z: ctx.airybi(z,1), -U(3*ctx.pi*(4*k-1)/8)) return ctx.findroot(ctx.airybi, -T(3*ctx.pi*(4*k-3)/8)) if which == 1 and complex == True: if derivative: t = 3*ctx.pi*(4*k-3)/8 + 0.75j*ctx.ln2 s = ctx.expjpi(ctx.mpf(1)/3) * T(t) return ctx.findroot(lambda z: ctx.airybi(z,1), s) t = 3*ctx.pi*(4*k-1)/8 + 0.75j*ctx.ln2 s = ctx.expjpi(ctx.mpf(1)/3) * U(t) return ctx.findroot(ctx.airybi, s) @defun def airyaizero(ctx, k, derivative=0): return _airy_zero(ctx, 0, k, derivative, False) @defun def airybizero(ctx, k, derivative=0, complex=False): return _airy_zero(ctx, 1, k, derivative, complex) def _scorer(ctx, z, which, kwargs): z = ctx.convert(z) if ctx.isinf(z): if z == ctx.inf: if which == 0: return 1/z if which == 1: return z if z == ctx.ninf: return 1/z raise ValueError("essential singularity") if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if kwargs.get('derivative'): raise NotImplementedError # Direct asymptotic expansions, to avoid # exponentially large cancellation try: if ctx.mag(z) > 3: if which == 0 and abs(ctx.arg(z)) < ctx.pi/3 * 0.999: def h(): return (([ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) if which == 1 and abs(ctx.arg(-z)) < 2*ctx.pi/3 * 0.999: def h(): return (([-ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) except ctx.NoConvergence: pass def h(): A = ctx.airybi(z, **kwargs)/3 B = -2*ctx.pi if which == 1: A *= 2 B *= -1 ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec T1 = [A], [1], [], [], [], [], 0 T2 = [B,z], [-1,2], [], [], [1], [ctx.mpq_4_3,ctx.mpq_5_3], w return T1, T2 return ctx.hypercomb(h, [], **kwargs) @defun def scorergi(ctx, z, **kwargs): return _scorer(ctx, z, 0, kwargs) @defun def scorerhi(ctx, z, **kwargs): return _scorer(ctx, z, 1, kwargs) @defun_wrapped def coulombc(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return +_cache[l,eta][1] G3 = ctx.loggamma(2*l+2) G1 = ctx.loggamma(1+l+ctx.j*eta) G2 = ctx.loggamma(1+l-ctx.j*eta) v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3) if not (ctx.im(l) or ctx.im(eta)): v = ctx.re(v) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs): # Regular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should #ctx.prec += 10 def h(l, eta): try: jw = ctx.j*w jwz = ctx.fmul(jw, z, exact=True) jwz2 = ctx.fmul(jwz, -2, exact=True) C = ctx.coulombc(l, eta) T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \ [2*l+2], jwz2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \ (ctx.re(z) >= 0): v = ctx.re(v) return v @defun_wrapped def _coulomb_chi(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return _cache[l,eta][1] def terms(): l2 = -l-1 jeta = ctx.j*eta return [ctx.loggamma(1+l+jeta) * (-0.5j), ctx.loggamma(1+l-jeta) * (0.5j), ctx.loggamma(1+l2+jeta) * (0.5j), ctx.loggamma(1+l2-jeta) * (-0.5j), -(l+0.5)*ctx.pi] v = ctx.sum_accurately(terms, 1) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs): # Irregular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should if not ctx._im(l): l = ctx._re(l) # XXX: for isint def h(l, eta): # Force perturbation for integers and half-integers if ctx.isint(l*2): T1 = [0], [-1], [], [], [], [], 0 return (T1,) l2 = -l-1 try: chi = ctx._coulomb_chi(l, eta) jw = ctx.j*w s = ctx.sin(chi); c = ctx.cos(chi) C1 = ctx.coulombc(l,eta) C2 = ctx.coulombc(l2,eta) u = ctx.exp(jw*z) x = -2*jw*z T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \ [1+l+jw*eta], [2*l+2], x T2 = [-s, C2, z, u], [-1, 1, l2+1, 1], [], [], \ [1+l2+jw*eta], [2*l2+2], x return T1, T2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \ (ctx._re(z) >= 0): v = ctx._re(v) return v def mcmahon(ctx,kind,prime,v,m): """ Computes an estimate for the location of the Bessel function zero j_{v,m}, y_{v,m}, j'_{v,m} or y'_{v,m} using McMahon's asymptotic expansion (Abramowitz & Stegun 9.5.12-13, DLMF 20.21(vi)). Returns (r,err) where r is the estimated location of the root and err is a positive number estimating the error of the asymptotic expansion. """ u = 4*v**2 if kind == 1 and not prime: b = (4*m+2*v-1)*ctx.pi/4 if kind == 2 and not prime: b = (4*m+2*v-3)*ctx.pi/4 if kind == 1 and prime: b = (4*m+2*v-3)*ctx.pi/4 if kind == 2 and prime: b = (4*m+2*v-1)*ctx.pi/4 if not prime: s1 = b s2 = -(u-1)/(8*b) s3 = -4*(u-1)*(7*u-31)/(3*(8*b)**3) s4 = -32*(u-1)*(83*u**2-982*u+3779)/(15*(8*b)**5) s5 = -64*(u-1)*(6949*u**3-153855*u**2+1585743*u-6277237)/(105*(8*b)**7) if prime: s1 = b s2 = -(u+3)/(8*b) s3 = -4*(7*u**2+82*u-9)/(3*(8*b)**3) s4 = -32*(83*u**3+2075*u**2-3039*u+3537)/(15*(8*b)**5) s5 = -64*(6949*u**4+296492*u**3-1248002*u**2+7414380*u-5853627)/(105*(8*b)**7) terms = [s1,s2,s3,s4,s5] s = s1 err = 0.0 for i in range(1,len(terms)): if abs(terms[i]) < abs(terms[i-1]): s += terms[i] else: err = abs(terms[i]) if i == len(terms)-1: err = abs(terms[-1]) return s, err def generalized_bisection(ctx,f,a,b,n): """ Given f known to have exactly n simple roots within [a,b], return a list of n intervals isolating the roots and having opposite signs at the endpoints. TODO: this can be optimized, e.g. by reusing evaluation points. """ if n < 1: raise ValueError("n cannot be less than 1") N = n+1 points = [] signs = [] while 1: points = ctx.linspace(a,b,N) signs = [ctx.sign(f(x)) for x in points] ok_intervals = [(points[i],points[i+1]) for i in range(N-1) \ if signs[i]*signs[i+1] == -1] if len(ok_intervals) == n: return ok_intervals N = N*2 def find_in_interval(ctx, f, ab): return ctx.findroot(f, ab, solver='illinois', verify=False) def bessel_zero(ctx, kind, prime, v, m, isoltol=0.01, _interval_cache={}): prec = ctx.prec workprec = max(prec, ctx.mag(v), ctx.mag(m))+10 try: ctx.prec = workprec v = ctx.mpf(v) m = int(m) prime = int(prime) if v < 0: raise ValueError("v cannot be negative") if m < 1: raise ValueError("m cannot be less than 1") if not prime in (0,1): raise ValueError("prime should lie between 0 and 1") if kind == 1: if prime: f = lambda x: ctx.besselj(v,x,derivative=1) else: f = lambda x: ctx.besselj(v,x) if kind == 2: if prime: f = lambda x: ctx.bessely(v,x,derivative=1) else: f = lambda x: ctx.bessely(v,x) # The first root of J' is very close to 0 for small # orders, and this needs to be special-cased if kind == 1 and prime and m == 1: if v == 0: return ctx.zero if v <= 1: # TODO: use v <= j'_{v,1} < y_{v,1}? r = 2*ctx.sqrt(v*(1+v)/(v+2)) return find_in_interval(ctx, f, (r/10, 2*r)) if (kind,prime,v,m) in _interval_cache: return find_in_interval(ctx, f, _interval_cache[kind,prime,v,m]) r, err = mcmahon(ctx, kind, prime, v, m) if err < isoltol: return find_in_interval(ctx, f, (r-isoltol, r+isoltol)) # An x such that 0 < x < r_{v,1} if kind == 1 and not prime: low = 2.4 if kind == 1 and prime: low = 1.8 if kind == 2 and not prime: low = 0.8 if kind == 2 and prime: low = 2.0 n = m+1 while 1: r1, err = mcmahon(ctx, kind, prime, v, n) if err < isoltol: r2, err2 = mcmahon(ctx, kind, prime, v, n+1) intervals = generalized_bisection(ctx, f, low, 0.5*(r1+r2), n) for k, ab in enumerate(intervals): _interval_cache[kind,prime,v,k+1] = ab return find_in_interval(ctx, f, intervals[m-1]) else: n = n*2 finally: ctx.prec = prec @defun def besseljzero(ctx, v, m, derivative=0): r""" For a real order `\nu \ge 0` and a positive integer `m`, returns `j_{\nu,m}`, the `m`-th positive zero of the Bessel function of the first kind `J_{\nu}(z)` (see :func:`~mpmath.besselj`). Alternatively, with *derivative=1*, gives the first nonnegative simple zero `j'_{\nu,m}` of `J'_{\nu}(z)`. The indexing convention is that used by Abramowitz & Stegun and the DLMF. Note the special case `j'_{0,1} = 0`, while all other zeros are positive. In effect, only simple zeros are counted (all zeros of Bessel functions are simple except possibly `z = 0`) and `j_{\nu,m}` becomes a monotonic function of both `\nu` and `m`. The zeros are interlaced according to the inequalities .. math :: j'_{\nu,k} < j_{\nu,k} < j'_{\nu,k+1} j_{\nu,1} < j_{\nu+1,2} < j_{\nu,2} < j_{\nu+1,2} < j_{\nu,3} < \cdots **Examples** Initial zeros of the Bessel functions `J_0(z), J_1(z), J_2(z)`:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> besseljzero(0,1); besseljzero(0,2); besseljzero(0,3) 2.404825557695772768621632 5.520078110286310649596604 8.653727912911012216954199 >>> besseljzero(1,1); besseljzero(1,2); besseljzero(1,3) 3.831705970207512315614436 7.01558666981561875353705 10.17346813506272207718571 >>> besseljzero(2,1); besseljzero(2,2); besseljzero(2,3) 5.135622301840682556301402 8.417244140399864857783614 11.61984117214905942709415 Initial zeros of `J'_0(z), J'_1(z), J'_2(z)`:: 0.0 3.831705970207512315614436 7.01558666981561875353705 >>> besseljzero(1,1,1); besseljzero(1,2,1); besseljzero(1,3,1) 1.84118378134065930264363 5.331442773525032636884016 8.536316366346285834358961 >>> besseljzero(2,1,1); besseljzero(2,2,1); besseljzero(2,3,1) 3.054236928227140322755932 6.706133194158459146634394 9.969467823087595793179143 Zeros with large index:: >>> besseljzero(0,100); besseljzero(0,1000); besseljzero(0,10000) 313.3742660775278447196902 3140.807295225078628895545 31415.14114171350798533666 >>> besseljzero(5,100); besseljzero(5,1000); besseljzero(5,10000) 321.1893195676003157339222 3148.657306813047523500494 31422.9947255486291798943 >>> besseljzero(0,100,1); besseljzero(0,1000,1); besseljzero(0,10000,1) 311.8018681873704508125112 3139.236339643802482833973 31413.57032947022399485808 Zeros of functions with large order:: >>> besseljzero(50,1) 57.11689916011917411936228 >>> besseljzero(50,2) 62.80769876483536093435393 >>> besseljzero(50,100) 388.6936600656058834640981 >>> besseljzero(50,1,1) 52.99764038731665010944037 >>> besseljzero(50,2,1) 60.02631933279942589882363 >>> besseljzero(50,100,1) 387.1083151608726181086283 Zeros of functions with fractional order:: >>> besseljzero(0.5,1); besseljzero(1.5,1); besseljzero(2.25,4) 3.141592653589793238462643 4.493409457909064175307881 15.15657692957458622921634 Both `J_{\nu}(z)` and `J'_{\nu}(z)` can be expressed as infinite products over their zeros:: >>> v,z = 2, mpf(1) >>> (z/2)**v/gamma(v+1) * \ ... nprod(lambda k: 1-(z/besseljzero(v,k))**2, [1,inf]) ... 0.1149034849319004804696469 >>> besselj(v,z) 0.1149034849319004804696469 >>> (z/2)**(v-1)/2/gamma(v) * \ ... nprod(lambda k: 1-(z/besseljzero(v,k,1))**2, [1,inf]) ... 0.2102436158811325550203884 >>> besselj(v,z,1) 0.2102436158811325550203884 """ return +bessel_zero(ctx, 1, derivative, v, m) @defun def besselyzero(ctx, v, m, derivative=0): r""" For a real order `\nu \ge 0` and a positive integer `m`, returns `y_{\nu,m}`, the `m`-th positive zero of the Bessel function of the second kind `Y_{\nu}(z)` (see :func:`~mpmath.bessely`). Alternatively, with *derivative=1*, gives the first positive zero `y'_{\nu,m}` of `Y'_{\nu}(z)`. The zeros are interlaced according to the inequalities .. math :: y_{\nu,k} < y'_{\nu,k} < y_{\nu,k+1} y_{\nu,1} < y_{\nu+1,2} < y_{\nu,2} < y_{\nu+1,2} < y_{\nu,3} < \cdots **Examples** Initial zeros of the Bessel functions `Y_0(z), Y_1(z), Y_2(z)`:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> besselyzero(0,1); besselyzero(0,2); besselyzero(0,3) 0.8935769662791675215848871 3.957678419314857868375677 7.086051060301772697623625 >>> besselyzero(1,1); besselyzero(1,2); besselyzero(1,3) 2.197141326031017035149034 5.429681040794135132772005 8.596005868331168926429606 >>> besselyzero(2,1); besselyzero(2,2); besselyzero(2,3) 3.384241767149593472701426 6.793807513268267538291167 10.02347797936003797850539 Initial zeros of `Y'_0(z), Y'_1(z), Y'_2(z)`:: >>> besselyzero(0,1,1); besselyzero(0,2,1); besselyzero(0,3,1) 2.197141326031017035149034 5.429681040794135132772005 8.596005868331168926429606 >>> besselyzero(1,1,1); besselyzero(1,2,1); besselyzero(1,3,1) 3.683022856585177699898967 6.941499953654175655751944 10.12340465543661307978775 >>> besselyzero(2,1,1); besselyzero(2,2,1); besselyzero(2,3,1) 5.002582931446063945200176 8.350724701413079526349714 11.57419546521764654624265 Zeros with large index:: >>> besselyzero(0,100); besselyzero(0,1000); besselyzero(0,10000) 311.8034717601871549333419 3139.236498918198006794026 31413.57034538691205229188 >>> besselyzero(5,100); besselyzero(5,1000); besselyzero(5,10000) 319.6183338562782156235062 3147.086508524556404473186 31421.42392920214673402828 >>> besselyzero(0,100,1); besselyzero(0,1000,1); besselyzero(0,10000,1) 313.3726705426359345050449 3140.807136030340213610065 31415.14112579761578220175 Zeros of functions with large order:: >>> besselyzero(50,1) 53.50285882040036394680237 >>> besselyzero(50,2) 60.11244442774058114686022 >>> besselyzero(50,100) 387.1096509824943957706835 >>> besselyzero(50,1,1) 56.96290427516751320063605 >>> besselyzero(50,2,1) 62.74888166945933944036623 >>> besselyzero(50,100,1) 388.6923300548309258355475 Zeros of functions with fractional order:: >>> besselyzero(0.5,1); besselyzero(1.5,1); besselyzero(2.25,4) 1.570796326794896619231322 2.798386045783887136720249 13.56721208770735123376018 """ return +bessel_zero(ctx, 2, derivative, v, m)
{ "repo_name": "klkuhlm/mpmath", "path": "mpmath/functions/bessel.py", "copies": "4", "size": "37938", "license": "bsd-3-clause", "hash": -4004448526894187000, "line_mean": 33.2400722022, "line_max": 100, "alpha_frac": 0.4871369076, "autogenerated": false, "ratio": 2.6792372881355933, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.012264356668547523, "num_lines": 1108 }
from functions import defun, defun_wrapped @defun def j0(ctx, x): """Computes the Bessel function `J_0(x)`. See :func:`~mpmath.besselj`.""" return ctx.besselj(0, x) @defun def j1(ctx, x): """Computes the Bessel function `J_1(x)`. See :func:`~mpmath.besselj`.""" return ctx.besselj(1, x) @defun def besselj(ctx, n, z, derivative=0, **kwargs): if type(n) is int: n_isint = True else: n = ctx.convert(n) n_isint = ctx.isint(n) if n_isint: n = int(ctx._re(n)) if n_isint and n < 0: return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs) z = ctx.convert(z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) # TODO: the integer special-casing shouldn't be necessary. # However, the hypergeometric series gets inaccurate for large d # because of inaccurate pole cancellation at a pole far from # zero (needs to be fixed in hypercomb or hypsum) if ctx.isint(d) and d >= 0: d = int(d) orig = ctx.prec try: ctx.prec += 15 v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z) for k in range(d+1)) finally: ctx.prec = orig v *= ctx.mpf(2)**(-d) else: def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2)] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20: try: return ctx._besselj(n, z) except NotImplementedError: pass if not z: if not n: v = ctx.one + n+z elif ctx.re(n) > 0: v = n*z else: v = ctx.inf + z + n else: #v = 0 orig = ctx.prec try: # XXX: workaround for accuracy in low level hypergeometric series # when alternating, large arguments ctx.prec += min(3*abs(M), ctx.prec) w = ctx.fmul(z, 0.5, exact=True) def h(n): r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) finally: ctx.prec = orig v = +v return v @defun def besseli(ctx, n, z, derivative=0, **kwargs): n = ctx.convert(n) z = ctx.convert(z) if not z: if derivative: raise ValueError if not n: # I(0,0) = 1 return 1+n+z if ctx.isint(n): return 0*(n+z) r = ctx.re(n) if r == 0: return ctx.nan*(n+z) elif r > 0: return 0*(n+z) else: return ctx.inf+(n+z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2), n+1] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: def h(n): w = ctx.fmul(z, 0.5, exact=True) r = ctx.fmul(w, w, prec=max(0,ctx.prec+M)) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) return v @defun_wrapped def bessely(ctx, n, z, derivative=0, **kwargs): if not z: if derivative: # Not implemented raise ValueError if not n: # ~ log(z/2) return -ctx.inf + (n+z) if ctx.im(n): return nan * (n+z) r = ctx.re(n) q = n+0.5 if ctx.isint(q): if n > 0: return -ctx.inf + (n+z) else: return 0 * (n+z) if r < 0 and int(ctx.floor(q)) % 2: return ctx.inf + (n+z) else: return ctx.ninf + (n+z) # XXX: use hypercomb ctx.prec += 10 m, d = ctx.nint_distance(n) if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 n += h elif d < 0: ctx.prec -= d # TODO: avoid cancellation for imaginary arguments cos, sin = ctx.cospi_sinpi(n) return (ctx.besselj(n,z,derivative,**kwargs)*cos - \ ctx.besselj(-n,z,derivative,**kwargs))/sin @defun_wrapped def besselk(ctx, n, z, **kwargs): if not z: return ctx.inf M = ctx.mag(z) if M < 1: # Represent as limit definition def h(n): r = (z/2)**2 T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r return T1, T2 # We could use the limit definition always, but it leads # to very bad cancellation (of exponentially large terms) # for large real z # Instead represent in terms of 2F0 else: ctx.prec += M def h(n): return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \ [n+0.5, 0.5-n], [], -1/(2*z))] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def hankel1(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def hankel2(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def whitm(ctx,k,m,z,**kwargs): if z == 0: # M(k,m,z) = 0^(1/2+m) if ctx.re(m) > -0.5: return z elif ctx.re(m) < -0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs) @defun_wrapped def whitw(ctx,k,m,z,**kwargs): if z == 0: g = abs(ctx.re(m)) if g < 0.5: return z elif g > 0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs) @defun def hyperu(ctx, a, b, z, **kwargs): a, atype = ctx._convert_param(a) b, btype = ctx._convert_param(b) z = ctx.convert(z) if not z: if ctx.re(b) <= 1: return ctx.gammaprod([1-b],[a-b+1]) else: return ctx.inf + z bb = 1+a-b bb, bbtype = ctx._convert_param(bb) try: orig = ctx.prec try: ctx.prec += 10 v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec) return v / z**a finally: ctx.prec = orig except ctx.NoConvergence: pass def h(a,b): w = ctx.sinpi(b) T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z) T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z) return T1, T2 return ctx.hypercomb(h, [a,b], **kwargs) @defun def struveh(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) @defun def struvel(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) def _anger(ctx,which,v,z,**kwargs): v = ctx._convert_param(v)[0] z = ctx.convert(z) def h(v): b = ctx.mpq_1_2 u = v*b m = b*3 a1,a2,b1,b2 = m-u, m+u, 1-u, 1+u c, s = ctx.cospi_sinpi(u) if which == 0: A, B = [b*z, s], [c] if which == 1: A, B = [b*z, -c], [s] w = ctx.square_exp_arg(z, mult=-0.25) T1 = A, [1, 1], [], [a1,a2], [1], [a1,a2], w T2 = B, [1], [], [b1,b2], [1], [b1,b2], w return T1, T2 return ctx.hypercomb(h, [v], **kwargs) @defun def angerj(ctx, v, z, **kwargs): return _anger(ctx, 0, v, z, **kwargs) @defun def webere(ctx, v, z, **kwargs): return _anger(ctx, 1, v, z, **kwargs) @defun def lommels1(ctx, u, v, z, **kwargs): u = ctx._convert_param(u)[0] v = ctx._convert_param(v)[0] z = ctx.convert(z) def h(u,v): b = ctx.mpq_1_2 w = ctx.square_exp_arg(z, mult=-0.25) return ([u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], \ [b*(u-v+3),b*(u+v+3)], w), return ctx.hypercomb(h, [u,v], **kwargs) @defun def lommels2(ctx, u, v, z, **kwargs): u = ctx._convert_param(u)[0] v = ctx._convert_param(v)[0] z = ctx.convert(z) # Asymptotic expansion (GR p. 947) -- need to be careful # not to use for small arguments # def h(u,v): # b = ctx.mpq_1_2 # w = -(z/2)**(-2) # return ([z], [u-1], [], [], [b*(1-u+v)], [b*(1-u-v)], w), def h(u,v): b = ctx.mpq_1_2 w = ctx.square_exp_arg(z, mult=-0.25) T1 = [u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], [b*(u-v+3),b*(u+v+3)], w T2 = [2, z], [u+v-1, -v], [v, b*(u+v+1)], [b*(v-u+1)], [], [1-v], w T3 = [2, z], [u-v-1, v], [-v, b*(u-v+1)], [b*(1-u-v)], [], [1+v], w #c1 = ctx.cospi((u-v)*b) #c2 = ctx.cospi((u+v)*b) #s = ctx.sinpi(v) #r1 = (u-v+1)*b #r2 = (u+v+1)*b #T2 = [c1, s, z, 2], [1, -1, -v, v], [], [-v+1], [], [-v+1], w #T3 = [-c2, s, z, 2], [1, -1, v, -v], [], [v+1], [], [v+1], w #T2 = [c1, s, z, 2], [1, -1, -v, v+u-1], [r1, r2], [-v+1], [], [-v+1], w #T3 = [-c2, s, z, 2], [1, -1, v, -v+u-1], [r1, r2], [v+1], [], [v+1], w return T1, T2, T3 return ctx.hypercomb(h, [u,v], **kwargs) @defun def ber(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos, sin = ctx.cospi_sinpi(-0.75*n) T1 = [cos, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r T2 = [sin, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def bei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos, sin = ctx.cospi_sinpi(0.75*n) T1 = [cos, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r T2 = [sin, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def ker(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos1, sin1 = ctx.cospi_sinpi(0.25*n) cos2, sin2 = ctx.cospi_sinpi(0.75*n) T1 = [2, z, 4*cos1], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r T2 = [2, z, -sin1], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r T3 = [2, z, 4*cos2], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T4 = [2, z, -sin2], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) @defun def kei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos1, sin1 = ctx.cospi_sinpi(0.75*n) cos2, sin2 = ctx.cospi_sinpi(0.25*n) T1 = [-cos1, 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r T2 = [-sin1, 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T3 = [-sin2, 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r T4 = [-cos2, 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) # TODO: do this more generically? def c_memo(f): name = f.__name__ def f_wrapped(ctx): cache = ctx._misc_const_cache prec = ctx.prec p,v = cache.get(name, (-1,0)) if p >= prec: return +v else: cache[name] = (prec, f(ctx)) return cache[name][1] return f_wrapped @c_memo def _airyai_C1(ctx): return 1 / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3)) @c_memo def _airyai_C2(ctx): return -1 / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3)) @c_memo def _airybi_C1(ctx): return 1 / (ctx.nthroot(3,6) * ctx.gamma(ctx.mpf(2)/3)) @c_memo def _airybi_C2(ctx): return ctx.nthroot(3,6) / ctx.gamma(ctx.mpf(1)/3) def _airybi_n2_inf(ctx): prec = ctx.prec try: v = ctx.power(3,'2/3')*ctx.gamma('2/3')/(2*ctx.pi) finally: ctx.prec = prec return +v # Derivatives at z = 0 # TODO: could be expressed more elegantly using triple factorials def _airyderiv_0(ctx, z, n, ntype, which): if ntype == 'Z': if n < 0: return z r = ctx.mpq_1_3 prec = ctx.prec try: ctx.prec += 10 v = ctx.gamma((n+1)*r) * ctx.power(3,n*r) / ctx.pi if which == 0: v *= ctx.sinpi(2*(n+1)*r) v /= ctx.power(3,'2/3') else: v *= abs(ctx.sinpi(2*(n+1)*r)) v /= ctx.power(3,'1/6') finally: ctx.prec = prec return +v + z else: # singular (does the limit exist?) raise NotImplementedError @defun def airyai(ctx, z, derivative=0, **kwargs): z = ctx.convert(z) if derivative: n, ntype = ctx._convert_param(derivative) else: n = 0 # Values at infinities if not ctx.isnormal(z) and z: if n and ntype == 'Z': if n == -1: if z == ctx.inf: return ctx.mpf(1)/3 + 1/z if z == ctx.ninf: return ctx.mpf(-2)/3 + 1/z if n < -1: if z == ctx.inf: return z if z == ctx.ninf: return (-1)**n * (-z) if (not n) and z == ctx.inf or z == ctx.ninf: return 1/z # TODO: limits raise ValueError("essential singularity of Ai(z)") # Account for exponential scaling if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if n: if n == 1: def h(): # http://functions.wolfram.com/03.07.06.0005.01 if ctx._re(z) > 4: ctx.prec += extraprec w = z**1.5; r = -0.75/w; u = -2*w/3 ctx.prec -= extraprec C = -ctx.exp(u)/(2*ctx.sqrt(ctx.pi))*ctx.nthroot(z,4) return ([C],[1],[],[],[(-1,6),(7,6)],[],r), # http://functions.wolfram.com/03.07.26.0001.01 else: ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airyai_C1(ctx) * 0.5 C2 = _airyai_C2(ctx) T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) else: if z == 0: return _airyderiv_0(ctx, z, n, ntype, 0) # http://functions.wolfram.com/03.05.20.0004.01 def h(n): ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 T1 = [3, z], [n-q23, -n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 T2 = [3, z, -z], [n-q43, -n, 1], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w return T1, T2 v = ctx.hypercomb(h, [n], **kwargs) if ctx._is_real_type(z) and ctx.isint(n): v = ctx._re(v) return v else: def h(): if ctx._re(z) > 4: # We could use 1F1, but it results in huge cancellation; # the following expansion is better. # TODO: asymptotic series for derivatives ctx.prec += extraprec w = z**1.5; r = -0.75/w; u = -2*w/3 ctx.prec -= extraprec C = ctx.exp(u)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4)) return ([C],[1],[],[],[(1,6),(5,6)],[],r), else: ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airyai_C1(ctx) C2 = _airyai_C2(ctx) T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) @defun def airybi(ctx, z, derivative=0, **kwargs): z = ctx.convert(z) if derivative: n, ntype = ctx._convert_param(derivative) else: n = 0 # Values at infinities if not ctx.isnormal(z) and z: if n and ntype == 'Z': if z == ctx.inf: return z if z == ctx.ninf: if n == -1: return 1/z if n == -2: return _airybi_n2_inf(ctx) if n < -2: return (-1)**n * (-z) if not n: if z == ctx.inf: return z if z == ctx.ninf: return 1/z # TODO: limits raise ValueError("essential singularity of Bi(z)") if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if n: if n == 1: # http://functions.wolfram.com/03.08.26.0001.01 def h(): ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airybi_C1(ctx)*0.5 C2 = _airybi_C2(ctx) T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) else: if z == 0: return _airyderiv_0(ctx, z, n, ntype, 1) def h(n): ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 q16 = ctx.mpq_1_6 q56 = ctx.mpq_5_6 a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 T1 = [3, z], [n-q16, -n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 T2 = [3, z], [n-q56, 1-n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w return T1, T2 v = ctx.hypercomb(h, [n], **kwargs) if ctx._is_real_type(z) and ctx.isint(n): v = ctx._re(v) return v else: def h(): ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airybi_C1(ctx) C2 = _airybi_C2(ctx) T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) def _airy_zero(ctx, which, k, derivative, complex=False): # Asymptotic formulas are given in DLMF section 9.9 def U(t): return t**(2/3.)*(1-7/(t**2*48)) def T(t): return t**(2/3.)*(1+5/(t**2*48)) k = int(k) assert k >= 1 assert derivative in (0,1) if which == 0: if derivative: return ctx.findroot(lambda z: ctx.airyai(z,1), -U(3*ctx.pi*(4*k-3)/8)) return ctx.findroot(ctx.airyai, -T(3*ctx.pi*(4*k-1)/8)) if which == 1 and complex == False: if derivative: return ctx.findroot(lambda z: ctx.airybi(z,1), -U(3*ctx.pi*(4*k-1)/8)) return ctx.findroot(ctx.airybi, -T(3*ctx.pi*(4*k-3)/8)) if which == 1 and complex == True: if derivative: t = 3*ctx.pi*(4*k-3)/8 + 0.75j*ctx.ln2 s = ctx.expjpi(ctx.mpf(1)/3) * T(t) return ctx.findroot(lambda z: ctx.airybi(z,1), s) t = 3*ctx.pi*(4*k-1)/8 + 0.75j*ctx.ln2 s = ctx.expjpi(ctx.mpf(1)/3) * U(t) return ctx.findroot(ctx.airybi, s) @defun def airyaizero(ctx, k, derivative=0): return _airy_zero(ctx, 0, k, derivative, False) @defun def airybizero(ctx, k, derivative=0, complex=False): return _airy_zero(ctx, 1, k, derivative, complex) def _scorer(ctx, z, which, kwargs): z = ctx.convert(z) if ctx.isinf(z): if z == ctx.inf: if which == 0: return 1/z if which == 1: return z if z == ctx.ninf: return 1/z raise ValueError("essential singularity") if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if kwargs.get('derivative'): raise NotImplementedError # Direct asymptotic expansions, to avoid # exponentially large cancellation try: if ctx.mag(z) > 3: if which == 0 and abs(ctx.arg(z)) < ctx.pi/3 * 0.999: def h(): return (([ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) if which == 1 and abs(ctx.arg(-z)) < 2*ctx.pi/3 * 0.999: def h(): return (([-ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) except ctx.NoConvergence: pass def h(): A = ctx.airybi(z, **kwargs)/3 B = -2*ctx.pi if which == 1: A *= 2 B *= -1 ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec T1 = [A], [1], [], [], [], [], 0 T2 = [B,z], [-1,2], [], [], [1], [ctx.mpq_4_3,ctx.mpq_5_3], w return T1, T2 return ctx.hypercomb(h, [], **kwargs) @defun def scorergi(ctx, z, **kwargs): return _scorer(ctx, z, 0, kwargs) @defun def scorerhi(ctx, z, **kwargs): return _scorer(ctx, z, 1, kwargs) @defun_wrapped def coulombc(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return +_cache[l,eta][1] G3 = ctx.loggamma(2*l+2) G1 = ctx.loggamma(1+l+ctx.j*eta) G2 = ctx.loggamma(1+l-ctx.j*eta) v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3) if not (ctx.im(l) or ctx.im(eta)): v = ctx.re(v) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs): # Regular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should #ctx.prec += 10 def h(l, eta): try: jw = ctx.j*w jwz = ctx.fmul(jw, z, exact=True) jwz2 = ctx.fmul(jwz, -2, exact=True) C = ctx.coulombc(l, eta) T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \ [2*l+2], jwz2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \ (ctx.re(z) >= 0): v = ctx.re(v) return v @defun_wrapped def _coulomb_chi(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return _cache[l,eta][1] def terms(): l2 = -l-1 jeta = ctx.j*eta return [ctx.loggamma(1+l+jeta) * (-0.5j), ctx.loggamma(1+l-jeta) * (0.5j), ctx.loggamma(1+l2+jeta) * (0.5j), ctx.loggamma(1+l2-jeta) * (-0.5j), -(l+0.5)*ctx.pi] v = ctx.sum_accurately(terms, 1) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs): # Irregular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should if not ctx._im(l): l = ctx._re(l) # XXX: for isint def h(l, eta): # Force perturbation for integers and half-integers if ctx.isint(l*2): T1 = [0], [-1], [], [], [], [], 0 return (T1,) l2 = -l-1 try: chi = ctx._coulomb_chi(l, eta) jw = ctx.j*w s = ctx.sin(chi); c = ctx.cos(chi) C1 = ctx.coulombc(l,eta) C2 = ctx.coulombc(l2,eta) u = ctx.exp(jw*z) x = -2*jw*z T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \ [1+l+jw*eta], [2*l+2], x T2 = [-s, C2, z, u], [-1, 1, l2+1, 1], [], [], \ [1+l2+jw*eta], [2*l2+2], x return T1, T2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \ (ctx._re(z) >= 0): v = ctx._re(v) return v def mcmahon(ctx,kind,prime,v,m): """ Computes an estimate for the location of the Bessel function zero j_{v,m}, y_{v,m}, j'_{v,m} or y'_{v,m} using McMahon's asymptotic expansion (Abramowitz & Stegun 9.5.12-13, DLMF 20.21(vi)). Returns (r,err) where r is the estimated location of the root and err is a positive number estimating the error of the asymptotic expansion. """ u = 4*v**2 if kind == 1 and not prime: b = (4*m+2*v-1)*ctx.pi/4 if kind == 2 and not prime: b = (4*m+2*v-3)*ctx.pi/4 if kind == 1 and prime: b = (4*m+2*v-3)*ctx.pi/4 if kind == 2 and prime: b = (4*m+2*v-1)*ctx.pi/4 if not prime: s1 = b s2 = -(u-1)/(8*b) s3 = -4*(u-1)*(7*u-31)/(3*(8*b)**3) s4 = -32*(u-1)*(83*u**2-982*u+3779)/(15*(8*b)**5) s5 = -64*(u-1)*(6949*u**3-153855*u**2+1585743*u-6277237)/(105*(8*b)**7) if prime: s1 = b s2 = -(u+3)/(8*b) s3 = -4*(7*u**2+82*u-9)/(3*(8*b)**3) s4 = -32*(83*u**3+2075*u**2-3039*u+3537)/(15*(8*b)**5) s5 = -64*(6949*u**4+296492*u**3-1248002*u**2+7414380*u-5853627)/(105*(8*b)**7) terms = [s1,s2,s3,s4,s5] s = s1 err = 0.0 for i in range(1,len(terms)): if abs(terms[i]) < abs(terms[i-1]): s += terms[i] else: err = abs(terms[i]) if i == len(terms)-1: err = abs(terms[-1]) return s, err def generalized_bisection(ctx,f,a,b,n): """ Given f known to have exactly n simple roots within [a,b], return a list of n intervals isolating the roots and having opposite signs at the endpoints. TODO: this can be optimized, e.g. by reusing evaluation points. """ assert n >= 1 N = n+1 points = [] signs = [] while 1: points = ctx.linspace(a,b,N) signs = [ctx.sign(f(x)) for x in points] ok_intervals = [(points[i],points[i+1]) for i in range(N-1) \ if signs[i]*signs[i+1] == -1] if len(ok_intervals) == n: return ok_intervals N = N*2 def find_in_interval(ctx, f, ab): return ctx.findroot(f, ab, solver='illinois', verify=False) def bessel_zero(ctx, kind, prime, v, m, isoltol=0.01, _interval_cache={}): prec = ctx.prec workprec = max(prec, ctx.mag(v), ctx.mag(m))+10 try: ctx.prec = workprec v = ctx.mpf(v) m = int(m) prime = int(prime) assert v >= 0 assert m >= 1 assert prime in (0,1) if kind == 1: if prime: f = lambda x: ctx.besselj(v,x,derivative=1) else: f = lambda x: ctx.besselj(v,x) if kind == 2: if prime: f = lambda x: ctx.bessely(v,x,derivative=1) else: f = lambda x: ctx.bessely(v,x) # The first root of J' is very close to 0 for small # orders, and this needs to be special-cased if kind == 1 and prime and m == 1: if v == 0: return ctx.zero if v <= 1: # TODO: use v <= j'_{v,1} < y_{v,1}? r = 2*ctx.sqrt(v*(1+v)/(v+2)) return find_in_interval(ctx, f, (r/10, 2*r)) if (kind,prime,v,m) in _interval_cache: return find_in_interval(ctx, f, _interval_cache[kind,prime,v,m]) r, err = mcmahon(ctx, kind, prime, v, m) if err < isoltol: return find_in_interval(ctx, f, (r-isoltol, r+isoltol)) # An x such that 0 < x < r_{v,1} if kind == 1 and not prime: low = 2.4 if kind == 1 and prime: low = 1.8 if kind == 2 and not prime: low = 0.8 if kind == 2 and prime: low = 2.0 n = m+1 while 1: r1, err = mcmahon(ctx, kind, prime, v, n) if err < isoltol: r2, err2 = mcmahon(ctx, kind, prime, v, n+1) intervals = generalized_bisection(ctx, f, low, 0.5*(r1+r2), n) for k, ab in enumerate(intervals): _interval_cache[kind,prime,v,k+1] = ab return find_in_interval(ctx, f, intervals[m-1]) else: n = n*2 finally: ctx.prec = prec @defun def besseljzero(ctx, v, m, derivative=0): r""" For a real order `\nu \ge 0` and a positive integer `m`, returns `j_{\nu,m}`, the `m`-th positive zero of the Bessel function of the first kind `J_{\nu}(z)` (see :func:`~mpmath.besselj`). Alternatively, with *derivative=1*, gives the first nonnegative simple zero `j'_{\nu,m}` of `J'_{\nu}(z)`. The indexing convention is that used by Abramowitz & Stegun and the DLMF. Note the special case `j'_{0,1} = 0`, while all other zeros are positive. In effect, only simple zeros are counted (all zeros of Bessel functions are simple except possibly `z = 0`) and `j_{\nu,m}` becomes a monotonic function of both `\nu` and `m`. The zeros are interlaced according to the inequalities .. math :: j'_{\nu,k} < j_{\nu,k} < j'_{\nu,k+1} j_{\nu,1} < j_{\nu+1,2} < j_{\nu,2} < j_{\nu+1,2} < j_{\nu,3} < \cdots **Examples** Initial zeros of the Bessel functions `J_0(z), J_1(z), J_2(z)`:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> besseljzero(0,1); besseljzero(0,2); besseljzero(0,3) 2.404825557695772768621632 5.520078110286310649596604 8.653727912911012216954199 >>> besseljzero(1,1); besseljzero(1,2); besseljzero(1,3) 3.831705970207512315614436 7.01558666981561875353705 10.17346813506272207718571 >>> besseljzero(2,1); besseljzero(2,2); besseljzero(2,3) 5.135622301840682556301402 8.417244140399864857783614 11.61984117214905942709415 Initial zeros of `J'_0(z), J'_1(z), J'_2(z)`:: 0.0 3.831705970207512315614436 7.01558666981561875353705 >>> besseljzero(1,1,1); besseljzero(1,2,1); besseljzero(1,3,1) 1.84118378134065930264363 5.331442773525032636884016 8.536316366346285834358961 >>> besseljzero(2,1,1); besseljzero(2,2,1); besseljzero(2,3,1) 3.054236928227140322755932 6.706133194158459146634394 9.969467823087595793179143 Zeros with large index:: >>> besseljzero(0,100); besseljzero(0,1000); besseljzero(0,10000) 313.3742660775278447196902 3140.807295225078628895545 31415.14114171350798533666 >>> besseljzero(5,100); besseljzero(5,1000); besseljzero(5,10000) 321.1893195676003157339222 3148.657306813047523500494 31422.9947255486291798943 >>> besseljzero(0,100,1); besseljzero(0,1000,1); besseljzero(0,10000,1) 311.8018681873704508125112 3139.236339643802482833973 31413.57032947022399485808 Zeros of functions with large order:: >>> besseljzero(50,1) 57.11689916011917411936228 >>> besseljzero(50,2) 62.80769876483536093435393 >>> besseljzero(50,100) 388.6936600656058834640981 >>> besseljzero(50,1,1) 52.99764038731665010944037 >>> besseljzero(50,2,1) 60.02631933279942589882363 >>> besseljzero(50,100,1) 387.1083151608726181086283 Zeros of functions with fractional order:: >>> besseljzero(0.5,1); besseljzero(1.5,1); besseljzero(2.25,4) 3.141592653589793238462643 4.493409457909064175307881 15.15657692957458622921634 Both `J_{\nu}(z)` and `J'_{\nu}(z)` can be expressed as infinite products over their zeros:: >>> v,z = 2, mpf(1) >>> (z/2)**v/gamma(v+1) * \ ... nprod(lambda k: 1-(z/besseljzero(v,k))**2, [1,inf]) ... 0.1149034849319004804696469 >>> besselj(v,z) 0.1149034849319004804696469 >>> (z/2)**(v-1)/2/gamma(v) * \ ... nprod(lambda k: 1-(z/besseljzero(v,k,1))**2, [1,inf]) ... 0.2102436158811325550203884 >>> besselj(v,z,1) 0.2102436158811325550203884 """ return +bessel_zero(ctx, 1, derivative, v, m) @defun def besselyzero(ctx, v, m, derivative=0): r""" For a real order `\nu \ge 0` and a positive integer `m`, returns `y_{\nu,m}`, the `m`-th positive zero of the Bessel function of the second kind `Y_{\nu}(z)` (see :func:`~mpmath.bessely`). Alternatively, with *derivative=1*, gives the first positive zero `y'_{\nu,m}` of `Y'_{\nu}(z)`. The zeros are interlaced according to the inequalities .. math :: y_{\nu,k} < y'_{\nu,k} < y_{\nu,k+1} y_{\nu,1} < y_{\nu+1,2} < y_{\nu,2} < y_{\nu+1,2} < y_{\nu,3} < \cdots **Examples** Initial zeros of the Bessel functions `Y_0(z), Y_1(z), Y_2(z)`:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> besselyzero(0,1); besselyzero(0,2); besselyzero(0,3) 0.8935769662791675215848871 3.957678419314857868375677 7.086051060301772697623625 >>> besselyzero(1,1); besselyzero(1,2); besselyzero(1,3) 2.197141326031017035149034 5.429681040794135132772005 8.596005868331168926429606 >>> besselyzero(2,1); besselyzero(2,2); besselyzero(2,3) 3.384241767149593472701426 6.793807513268267538291167 10.02347797936003797850539 Initial zeros of `Y'_0(z), Y'_1(z), Y'_2(z)`:: >>> besselyzero(0,1,1); besselyzero(0,2,1); besselyzero(0,3,1) 2.197141326031017035149034 5.429681040794135132772005 8.596005868331168926429606 >>> besselyzero(1,1,1); besselyzero(1,2,1); besselyzero(1,3,1) 3.683022856585177699898967 6.941499953654175655751944 10.12340465543661307978775 >>> besselyzero(2,1,1); besselyzero(2,2,1); besselyzero(2,3,1) 5.002582931446063945200176 8.350724701413079526349714 11.57419546521764654624265 Zeros with large index:: >>> besselyzero(0,100); besselyzero(0,1000); besselyzero(0,10000) 311.8034717601871549333419 3139.236498918198006794026 31413.57034538691205229188 >>> besselyzero(5,100); besselyzero(5,1000); besselyzero(5,10000) 319.6183338562782156235062 3147.086508524556404473186 31421.42392920214673402828 >>> besselyzero(0,100,1); besselyzero(0,1000,1); besselyzero(0,10000,1) 313.3726705426359345050449 3140.807136030340213610065 31415.14112579761578220175 Zeros of functions with large order:: >>> besselyzero(50,1) 53.50285882040036394680237 >>> besselyzero(50,2) 60.11244442774058114686022 >>> besselyzero(50,100) 387.1096509824943957706835 >>> besselyzero(50,1,1) 56.96290427516751320063605 >>> besselyzero(50,2,1) 62.74888166945933944036623 >>> besselyzero(50,100,1) 388.6923300548309258355475 Zeros of functions with fractional order:: >>> besselyzero(0.5,1); besselyzero(1.5,1); besselyzero(2.25,4) 1.570796326794896619231322 2.798386045783887136720249 13.56721208770735123376018 """ return +bessel_zero(ctx, 2, derivative, v, m)
{ "repo_name": "pernici/sympy", "path": "sympy/mpmath/functions/bessel.py", "copies": "2", "size": "37599", "license": "bsd-3-clause", "hash": 9191072003030575000, "line_mean": 33.1188747731, "line_max": 100, "alpha_frac": 0.4861299503, "autogenerated": false, "ratio": 2.670004260758415, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4156134211058415, "avg_score": null, "num_lines": null }
from .functions import defun, defun_wrapped @defun def j0(ctx, x): """Computes the Bessel function `J_0(x)`. See :func:`~mpmath.besselj`.""" return ctx.besselj(0, x) @defun def j1(ctx, x): """Computes the Bessel function `J_1(x)`. See :func:`~mpmath.besselj`.""" return ctx.besselj(1, x) @defun def besselj(ctx, n, z, derivative=0, **kwargs): if type(n) is int: n_isint = True else: n = ctx.convert(n) n_isint = ctx.isint(n) if n_isint: n = int(ctx._re(n)) if n_isint and n < 0: return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs) z = ctx.convert(z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) # TODO: the integer special-casing shouldn't be necessary. # However, the hypergeometric series gets inaccurate for large d # because of inaccurate pole cancellation at a pole far from # zero (needs to be fixed in hypercomb or hypsum) if ctx.isint(d) and d >= 0: d = int(d) orig = ctx.prec try: ctx.prec += 15 v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z) for k in range(d+1)) finally: ctx.prec = orig v *= ctx.mpf(2)**(-d) else: def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2)] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20: try: return ctx._besselj(n, z) except NotImplementedError: pass if not z: if not n: v = ctx.one + n+z elif ctx.re(n) > 0: v = n*z else: v = ctx.inf + z + n else: #v = 0 orig = ctx.prec try: # XXX: workaround for accuracy in low level hypergeometric series # when alternating, large arguments ctx.prec += min(3*abs(M), ctx.prec) w = ctx.fmul(z, 0.5, exact=True) def h(n): r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) finally: ctx.prec = orig v = +v return v @defun def besseli(ctx, n, z, derivative=0, **kwargs): n = ctx.convert(n) z = ctx.convert(z) if not z: if derivative: raise ValueError if not n: # I(0,0) = 1 return 1+n+z if ctx.isint(n): return 0*(n+z) r = ctx.re(n) if r == 0: return ctx.nan*(n+z) elif r > 0: return 0*(n+z) else: return ctx.inf+(n+z) M = ctx.mag(z) if derivative: d = ctx.convert(derivative) def h(n,d): r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True) B = [0.5*(n-d+1), 0.5*(n-d+2), n+1] T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)] return T v = ctx.hypercomb(h, [n,d], **kwargs) else: def h(n): w = ctx.fmul(z, 0.5, exact=True) r = ctx.fmul(w, w, prec=max(0,ctx.prec+M)) return [([w], [n], [], [n+1], [], [n+1], r)] v = ctx.hypercomb(h, [n], **kwargs) return v @defun_wrapped def bessely(ctx, n, z, derivative=0, **kwargs): if not z: if derivative: # Not implemented raise ValueError if not n: # ~ log(z/2) return -ctx.inf + (n+z) if ctx.im(n): return nan * (n+z) r = ctx.re(n) q = n+0.5 if ctx.isint(q): if n > 0: return -ctx.inf + (n+z) else: return 0 * (n+z) if r < 0 and int(ctx.floor(q)) % 2: return ctx.inf + (n+z) else: return ctx.ninf + (n+z) # XXX: use hypercomb ctx.prec += 10 m, d = ctx.nint_distance(n) if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 n += h elif d < 0: ctx.prec -= d # TODO: avoid cancellation for imaginary arguments cos, sin = ctx.cospi_sinpi(n) return (ctx.besselj(n,z,derivative,**kwargs)*cos - \ ctx.besselj(-n,z,derivative,**kwargs))/sin @defun_wrapped def besselk(ctx, n, z, **kwargs): if not z: return ctx.inf M = ctx.mag(z) if M < 1: # Represent as limit definition def h(n): r = (z/2)**2 T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r return T1, T2 # We could use the limit definition always, but it leads # to very bad cancellation (of exponentially large terms) # for large real z # Instead represent in terms of 2F0 else: ctx.prec += M def h(n): return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \ [n+0.5, 0.5-n], [], -1/(2*z))] return ctx.hypercomb(h, [n], **kwargs) @defun_wrapped def hankel1(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def hankel2(ctx,n,x,**kwargs): return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs) @defun_wrapped def whitm(ctx,k,m,z,**kwargs): if z == 0: # M(k,m,z) = 0^(1/2+m) if ctx.re(m) > -0.5: return z elif ctx.re(m) < -0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs) @defun_wrapped def whitw(ctx,k,m,z,**kwargs): if z == 0: g = abs(ctx.re(m)) if g < 0.5: return z elif g > 0.5: return ctx.inf + z else: return ctx.nan * z x = ctx.fmul(-0.5, z, exact=True) y = 0.5+m return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs) @defun def hyperu(ctx, a, b, z, **kwargs): a, atype = ctx._convert_param(a) b, btype = ctx._convert_param(b) z = ctx.convert(z) if not z: if ctx.re(b) <= 1: return ctx.gammaprod([1-b],[a-b+1]) else: return ctx.inf + z bb = 1+a-b bb, bbtype = ctx._convert_param(bb) try: orig = ctx.prec try: ctx.prec += 10 v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec) return v / z**a finally: ctx.prec = orig except ctx.NoConvergence: pass def h(a,b): w = ctx.sinpi(b) T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z) T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z) return T1, T2 return ctx.hypercomb(h, [a,b], **kwargs) @defun def struveh(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) @defun def struvel(ctx,n,z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/ def h(n): return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)] return ctx.hypercomb(h, [n], **kwargs) def _anger(ctx,which,v,z,**kwargs): v = ctx._convert_param(v)[0] z = ctx.convert(z) def h(v): b = ctx.mpq_1_2 u = v*b m = b*3 a1,a2,b1,b2 = m-u, m+u, 1-u, 1+u c, s = ctx.cospi_sinpi(u) if which == 0: A, B = [b*z, s], [c] if which == 1: A, B = [b*z, -c], [s] w = ctx.square_exp_arg(z, mult=-0.25) T1 = A, [1, 1], [], [a1,a2], [1], [a1,a2], w T2 = B, [1], [], [b1,b2], [1], [b1,b2], w return T1, T2 return ctx.hypercomb(h, [v], **kwargs) @defun def angerj(ctx, v, z, **kwargs): return _anger(ctx, 0, v, z, **kwargs) @defun def webere(ctx, v, z, **kwargs): return _anger(ctx, 1, v, z, **kwargs) @defun def lommels1(ctx, u, v, z, **kwargs): u = ctx._convert_param(u)[0] v = ctx._convert_param(v)[0] z = ctx.convert(z) def h(u,v): b = ctx.mpq_1_2 w = ctx.square_exp_arg(z, mult=-0.25) return ([u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], \ [b*(u-v+3),b*(u+v+3)], w), return ctx.hypercomb(h, [u,v], **kwargs) @defun def lommels2(ctx, u, v, z, **kwargs): u = ctx._convert_param(u)[0] v = ctx._convert_param(v)[0] z = ctx.convert(z) # Asymptotic expansion (GR p. 947) -- need to be careful # not to use for small arguments # def h(u,v): # b = ctx.mpq_1_2 # w = -(z/2)**(-2) # return ([z], [u-1], [], [], [b*(1-u+v)], [b*(1-u-v)], w), def h(u,v): b = ctx.mpq_1_2 w = ctx.square_exp_arg(z, mult=-0.25) T1 = [u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], [b*(u-v+3),b*(u+v+3)], w T2 = [2, z], [u+v-1, -v], [v, b*(u+v+1)], [b*(v-u+1)], [], [1-v], w T3 = [2, z], [u-v-1, v], [-v, b*(u-v+1)], [b*(1-u-v)], [], [1+v], w #c1 = ctx.cospi((u-v)*b) #c2 = ctx.cospi((u+v)*b) #s = ctx.sinpi(v) #r1 = (u-v+1)*b #r2 = (u+v+1)*b #T2 = [c1, s, z, 2], [1, -1, -v, v], [], [-v+1], [], [-v+1], w #T3 = [-c2, s, z, 2], [1, -1, v, -v], [], [v+1], [], [v+1], w #T2 = [c1, s, z, 2], [1, -1, -v, v+u-1], [r1, r2], [-v+1], [], [-v+1], w #T3 = [-c2, s, z, 2], [1, -1, v, -v+u-1], [r1, r2], [v+1], [], [v+1], w return T1, T2, T3 return ctx.hypercomb(h, [u,v], **kwargs) @defun def ber(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos, sin = ctx.cospi_sinpi(-0.75*n) T1 = [cos, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r T2 = [sin, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def bei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos, sin = ctx.cospi_sinpi(0.75*n) T1 = [cos, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r T2 = [sin, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r return T1, T2 return ctx.hypercomb(h, [n], **kwargs) @defun def ker(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos1, sin1 = ctx.cospi_sinpi(0.25*n) cos2, sin2 = ctx.cospi_sinpi(0.75*n) T1 = [2, z, 4*cos1], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r T2 = [2, z, -sin1], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r T3 = [2, z, 4*cos2], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T4 = [2, z, -sin2], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) @defun def kei(ctx, n, z, **kwargs): n = ctx.convert(n) z = ctx.convert(z) # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/ def h(n): r = -(z/4)**4 cos1, sin1 = ctx.cospi_sinpi(0.75*n) cos2, sin2 = ctx.cospi_sinpi(0.25*n) T1 = [-cos1, 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r T2 = [-sin1, 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r T3 = [-sin2, 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r T4 = [-cos2, 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r return T1, T2, T3, T4 return ctx.hypercomb(h, [n], **kwargs) # TODO: do this more generically? def c_memo(f): name = f.__name__ def f_wrapped(ctx): cache = ctx._misc_const_cache prec = ctx.prec p,v = cache.get(name, (-1,0)) if p >= prec: return +v else: cache[name] = (prec, f(ctx)) return cache[name][1] return f_wrapped @c_memo def _airyai_C1(ctx): return 1 / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3)) @c_memo def _airyai_C2(ctx): return -1 / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3)) @c_memo def _airybi_C1(ctx): return 1 / (ctx.nthroot(3,6) * ctx.gamma(ctx.mpf(2)/3)) @c_memo def _airybi_C2(ctx): return ctx.nthroot(3,6) / ctx.gamma(ctx.mpf(1)/3) def _airybi_n2_inf(ctx): prec = ctx.prec try: v = ctx.power(3,'2/3')*ctx.gamma('2/3')/(2*ctx.pi) finally: ctx.prec = prec return +v # Derivatives at z = 0 # TODO: could be expressed more elegantly using triple factorials def _airyderiv_0(ctx, z, n, ntype, which): if ntype == 'Z': if n < 0: return z r = ctx.mpq_1_3 prec = ctx.prec try: ctx.prec += 10 v = ctx.gamma((n+1)*r) * ctx.power(3,n*r) / ctx.pi if which == 0: v *= ctx.sinpi(2*(n+1)*r) v /= ctx.power(3,'2/3') else: v *= abs(ctx.sinpi(2*(n+1)*r)) v /= ctx.power(3,'1/6') finally: ctx.prec = prec return +v + z else: # singular (does the limit exist?) raise NotImplementedError @defun def airyai(ctx, z, derivative=0, **kwargs): z = ctx.convert(z) if derivative: n, ntype = ctx._convert_param(derivative) else: n = 0 # Values at infinities if not ctx.isnormal(z) and z: if n and ntype == 'Z': if n == -1: if z == ctx.inf: return ctx.mpf(1)/3 + 1/z if z == ctx.ninf: return ctx.mpf(-2)/3 + 1/z if n < -1: if z == ctx.inf: return z if z == ctx.ninf: return (-1)**n * (-z) if (not n) and z == ctx.inf or z == ctx.ninf: return 1/z # TODO: limits raise ValueError("essential singularity of Ai(z)") # Account for exponential scaling if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if n: if n == 1: def h(): # http://functions.wolfram.com/03.07.06.0005.01 if ctx._re(z) > 4: ctx.prec += extraprec w = z**1.5; r = -0.75/w; u = -2*w/3 ctx.prec -= extraprec C = -ctx.exp(u)/(2*ctx.sqrt(ctx.pi))*ctx.nthroot(z,4) return ([C],[1],[],[],[(-1,6),(7,6)],[],r), # http://functions.wolfram.com/03.07.26.0001.01 else: ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airyai_C1(ctx) * 0.5 C2 = _airyai_C2(ctx) T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) else: if z == 0: return _airyderiv_0(ctx, z, n, ntype, 0) # http://functions.wolfram.com/03.05.20.0004.01 def h(n): ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 T1 = [3, z], [n-q23, -n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 T2 = [3, z, -z], [n-q43, -n, 1], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w return T1, T2 v = ctx.hypercomb(h, [n], **kwargs) if ctx._is_real_type(z) and ctx.isint(n): v = ctx._re(v) return v else: def h(): if ctx._re(z) > 4: # We could use 1F1, but it results in huge cancellation; # the following expansion is better. # TODO: asymptotic series for derivatives ctx.prec += extraprec w = z**1.5; r = -0.75/w; u = -2*w/3 ctx.prec -= extraprec C = ctx.exp(u)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4)) return ([C],[1],[],[],[(1,6),(5,6)],[],r), else: ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airyai_C1(ctx) C2 = _airyai_C2(ctx) T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) @defun def airybi(ctx, z, derivative=0, **kwargs): z = ctx.convert(z) if derivative: n, ntype = ctx._convert_param(derivative) else: n = 0 # Values at infinities if not ctx.isnormal(z) and z: if n and ntype == 'Z': if z == ctx.inf: return z if z == ctx.ninf: if n == -1: return 1/z if n == -2: return _airybi_n2_inf(ctx) if n < -2: return (-1)**n * (-z) if not n: if z == ctx.inf: return z if z == ctx.ninf: return 1/z # TODO: limits raise ValueError("essential singularity of Bi(z)") if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if n: if n == 1: # http://functions.wolfram.com/03.08.26.0001.01 def h(): ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airybi_C1(ctx)*0.5 C2 = _airybi_C2(ctx) T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) else: if z == 0: return _airyderiv_0(ctx, z, n, ntype, 1) def h(n): ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 q16 = ctx.mpq_1_6 q56 = ctx.mpq_5_6 a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 T1 = [3, z], [n-q16, -n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 T2 = [3, z], [n-q56, 1-n], [a1], [b1,b2,b3], \ [a1,a2], [b1,b2,b3], w return T1, T2 v = ctx.hypercomb(h, [n], **kwargs) if ctx._is_real_type(z) and ctx.isint(n): v = ctx._re(v) return v else: def h(): ctx.prec += extraprec w = z**3 / 9 ctx.prec -= extraprec C1 = _airybi_C1(ctx) C2 = _airybi_C2(ctx) T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w return T1, T2 return ctx.hypercomb(h, [], **kwargs) def _airy_zero(ctx, which, k, derivative, complex=False): # Asymptotic formulas are given in DLMF section 9.9 def U(t): return t**(2/3.)*(1-7/(t**2*48)) def T(t): return t**(2/3.)*(1+5/(t**2*48)) k = int(k) if k < 1: raise ValueError("k cannot be less than 1") if not derivative in (0,1): raise ValueError("Derivative should lie between 0 and 1") if which == 0: if derivative: return ctx.findroot(lambda z: ctx.airyai(z,1), -U(3*ctx.pi*(4*k-3)/8)) return ctx.findroot(ctx.airyai, -T(3*ctx.pi*(4*k-1)/8)) if which == 1 and complex == False: if derivative: return ctx.findroot(lambda z: ctx.airybi(z,1), -U(3*ctx.pi*(4*k-1)/8)) return ctx.findroot(ctx.airybi, -T(3*ctx.pi*(4*k-3)/8)) if which == 1 and complex == True: if derivative: t = 3*ctx.pi*(4*k-3)/8 + 0.75j*ctx.ln2 s = ctx.expjpi(ctx.mpf(1)/3) * T(t) return ctx.findroot(lambda z: ctx.airybi(z,1), s) t = 3*ctx.pi*(4*k-1)/8 + 0.75j*ctx.ln2 s = ctx.expjpi(ctx.mpf(1)/3) * U(t) return ctx.findroot(ctx.airybi, s) @defun def airyaizero(ctx, k, derivative=0): return _airy_zero(ctx, 0, k, derivative, False) @defun def airybizero(ctx, k, derivative=0, complex=False): return _airy_zero(ctx, 1, k, derivative, complex) def _scorer(ctx, z, which, kwargs): z = ctx.convert(z) if ctx.isinf(z): if z == ctx.inf: if which == 0: return 1/z if which == 1: return z if z == ctx.ninf: return 1/z raise ValueError("essential singularity") if z: extraprec = max(0, int(1.5*ctx.mag(z))) else: extraprec = 0 if kwargs.get('derivative'): raise NotImplementedError # Direct asymptotic expansions, to avoid # exponentially large cancellation try: if ctx.mag(z) > 3: if which == 0 and abs(ctx.arg(z)) < ctx.pi/3 * 0.999: def h(): return (([ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) if which == 1 and abs(ctx.arg(-z)) < 2*ctx.pi/3 * 0.999: def h(): return (([-ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) except ctx.NoConvergence: pass def h(): A = ctx.airybi(z, **kwargs)/3 B = -2*ctx.pi if which == 1: A *= 2 B *= -1 ctx.prec += extraprec w = z**3/9 ctx.prec -= extraprec T1 = [A], [1], [], [], [], [], 0 T2 = [B,z], [-1,2], [], [], [1], [ctx.mpq_4_3,ctx.mpq_5_3], w return T1, T2 return ctx.hypercomb(h, [], **kwargs) @defun def scorergi(ctx, z, **kwargs): return _scorer(ctx, z, 0, kwargs) @defun def scorerhi(ctx, z, **kwargs): return _scorer(ctx, z, 1, kwargs) @defun_wrapped def coulombc(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return +_cache[l,eta][1] G3 = ctx.loggamma(2*l+2) G1 = ctx.loggamma(1+l+ctx.j*eta) G2 = ctx.loggamma(1+l-ctx.j*eta) v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3) if not (ctx.im(l) or ctx.im(eta)): v = ctx.re(v) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs): # Regular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should #ctx.prec += 10 def h(l, eta): try: jw = ctx.j*w jwz = ctx.fmul(jw, z, exact=True) jwz2 = ctx.fmul(jwz, -2, exact=True) C = ctx.coulombc(l, eta) T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \ [2*l+2], jwz2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \ (ctx.re(z) >= 0): v = ctx.re(v) return v @defun_wrapped def _coulomb_chi(ctx, l, eta, _cache={}): if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: return _cache[l,eta][1] def terms(): l2 = -l-1 jeta = ctx.j*eta return [ctx.loggamma(1+l+jeta) * (-0.5j), ctx.loggamma(1+l-jeta) * (0.5j), ctx.loggamma(1+l2+jeta) * (0.5j), ctx.loggamma(1+l2-jeta) * (-0.5j), -(l+0.5)*ctx.pi] v = ctx.sum_accurately(terms, 1) _cache[l,eta] = (ctx.prec, v) return v @defun_wrapped def coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs): # Irregular Coulomb wave function # Note: w can be either 1 or -1; the other may be better in some cases # TODO: check that chop=True chops when and only when it should if not ctx._im(l): l = ctx._re(l) # XXX: for isint def h(l, eta): # Force perturbation for integers and half-integers if ctx.isint(l*2): T1 = [0], [-1], [], [], [], [], 0 return (T1,) l2 = -l-1 try: chi = ctx._coulomb_chi(l, eta) jw = ctx.j*w s = ctx.sin(chi); c = ctx.cos(chi) C1 = ctx.coulombc(l,eta) C2 = ctx.coulombc(l2,eta) u = ctx.exp(jw*z) x = -2*jw*z T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \ [1+l+jw*eta], [2*l+2], x T2 = [-s, C2, z, u], [-1, 1, l2+1, 1], [], [], \ [1+l2+jw*eta], [2*l2+2], x return T1, T2 except ValueError: T1 = [0], [-1], [], [], [], [], 0 return (T1,) v = ctx.hypercomb(h, [l,eta], **kwargs) if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \ (ctx._re(z) >= 0): v = ctx._re(v) return v def mcmahon(ctx,kind,prime,v,m): """ Computes an estimate for the location of the Bessel function zero j_{v,m}, y_{v,m}, j'_{v,m} or y'_{v,m} using McMahon's asymptotic expansion (Abramowitz & Stegun 9.5.12-13, DLMF 20.21(vi)). Returns (r,err) where r is the estimated location of the root and err is a positive number estimating the error of the asymptotic expansion. """ u = 4*v**2 if kind == 1 and not prime: b = (4*m+2*v-1)*ctx.pi/4 if kind == 2 and not prime: b = (4*m+2*v-3)*ctx.pi/4 if kind == 1 and prime: b = (4*m+2*v-3)*ctx.pi/4 if kind == 2 and prime: b = (4*m+2*v-1)*ctx.pi/4 if not prime: s1 = b s2 = -(u-1)/(8*b) s3 = -4*(u-1)*(7*u-31)/(3*(8*b)**3) s4 = -32*(u-1)*(83*u**2-982*u+3779)/(15*(8*b)**5) s5 = -64*(u-1)*(6949*u**3-153855*u**2+1585743*u-6277237)/(105*(8*b)**7) if prime: s1 = b s2 = -(u+3)/(8*b) s3 = -4*(7*u**2+82*u-9)/(3*(8*b)**3) s4 = -32*(83*u**3+2075*u**2-3039*u+3537)/(15*(8*b)**5) s5 = -64*(6949*u**4+296492*u**3-1248002*u**2+7414380*u-5853627)/(105*(8*b)**7) terms = [s1,s2,s3,s4,s5] s = s1 err = 0.0 for i in range(1,len(terms)): if abs(terms[i]) < abs(terms[i-1]): s += terms[i] else: err = abs(terms[i]) if i == len(terms)-1: err = abs(terms[-1]) return s, err def generalized_bisection(ctx,f,a,b,n): """ Given f known to have exactly n simple roots within [a,b], return a list of n intervals isolating the roots and having opposite signs at the endpoints. TODO: this can be optimized, e.g. by reusing evaluation points. """ if n < 1: raise ValueError("n cannot be less than 1") N = n+1 points = [] signs = [] while 1: points = ctx.linspace(a,b,N) signs = [ctx.sign(f(x)) for x in points] ok_intervals = [(points[i],points[i+1]) for i in range(N-1) \ if signs[i]*signs[i+1] == -1] if len(ok_intervals) == n: return ok_intervals N = N*2 def find_in_interval(ctx, f, ab): return ctx.findroot(f, ab, solver='illinois', verify=False) def bessel_zero(ctx, kind, prime, v, m, isoltol=0.01, _interval_cache={}): prec = ctx.prec workprec = max(prec, ctx.mag(v), ctx.mag(m))+10 try: ctx.prec = workprec v = ctx.mpf(v) m = int(m) prime = int(prime) if v < 0: raise ValueError("v cannot be negative") if m < 1: raise ValueError("m cannot be less than 1") if not prime in (0,1): raise ValueError("prime should lie between 0 and 1") if kind == 1: if prime: f = lambda x: ctx.besselj(v,x,derivative=1) else: f = lambda x: ctx.besselj(v,x) if kind == 2: if prime: f = lambda x: ctx.bessely(v,x,derivative=1) else: f = lambda x: ctx.bessely(v,x) # The first root of J' is very close to 0 for small # orders, and this needs to be special-cased if kind == 1 and prime and m == 1: if v == 0: return ctx.zero if v <= 1: # TODO: use v <= j'_{v,1} < y_{v,1}? r = 2*ctx.sqrt(v*(1+v)/(v+2)) return find_in_interval(ctx, f, (r/10, 2*r)) if (kind,prime,v,m) in _interval_cache: return find_in_interval(ctx, f, _interval_cache[kind,prime,v,m]) r, err = mcmahon(ctx, kind, prime, v, m) if err < isoltol: return find_in_interval(ctx, f, (r-isoltol, r+isoltol)) # An x such that 0 < x < r_{v,1} if kind == 1 and not prime: low = 2.4 if kind == 1 and prime: low = 1.8 if kind == 2 and not prime: low = 0.8 if kind == 2 and prime: low = 2.0 n = m+1 while 1: r1, err = mcmahon(ctx, kind, prime, v, n) if err < isoltol: r2, err2 = mcmahon(ctx, kind, prime, v, n+1) intervals = generalized_bisection(ctx, f, low, 0.5*(r1+r2), n) for k, ab in enumerate(intervals): _interval_cache[kind,prime,v,k+1] = ab return find_in_interval(ctx, f, intervals[m-1]) else: n = n*2 finally: ctx.prec = prec @defun def besseljzero(ctx, v, m, derivative=0): r""" For a real order `\nu \ge 0` and a positive integer `m`, returns `j_{\nu,m}`, the `m`-th positive zero of the Bessel function of the first kind `J_{\nu}(z)` (see :func:`~mpmath.besselj`). Alternatively, with *derivative=1*, gives the first nonnegative simple zero `j'_{\nu,m}` of `J'_{\nu}(z)`. The indexing convention is that used by Abramowitz & Stegun and the DLMF. Note the special case `j'_{0,1} = 0`, while all other zeros are positive. In effect, only simple zeros are counted (all zeros of Bessel functions are simple except possibly `z = 0`) and `j_{\nu,m}` becomes a monotonic function of both `\nu` and `m`. The zeros are interlaced according to the inequalities .. math :: j'_{\nu,k} < j_{\nu,k} < j'_{\nu,k+1} j_{\nu,1} < j_{\nu+1,2} < j_{\nu,2} < j_{\nu+1,2} < j_{\nu,3} < \cdots **Examples** Initial zeros of the Bessel functions `J_0(z), J_1(z), J_2(z)`:: >>> from sympy.mpmath import * >>> mp.dps = 25; mp.pretty = True >>> besseljzero(0,1); besseljzero(0,2); besseljzero(0,3) 2.404825557695772768621632 5.520078110286310649596604 8.653727912911012216954199 >>> besseljzero(1,1); besseljzero(1,2); besseljzero(1,3) 3.831705970207512315614436 7.01558666981561875353705 10.17346813506272207718571 >>> besseljzero(2,1); besseljzero(2,2); besseljzero(2,3) 5.135622301840682556301402 8.417244140399864857783614 11.61984117214905942709415 Initial zeros of `J'_0(z), J'_1(z), J'_2(z)`:: 0.0 3.831705970207512315614436 7.01558666981561875353705 >>> besseljzero(1,1,1); besseljzero(1,2,1); besseljzero(1,3,1) 1.84118378134065930264363 5.331442773525032636884016 8.536316366346285834358961 >>> besseljzero(2,1,1); besseljzero(2,2,1); besseljzero(2,3,1) 3.054236928227140322755932 6.706133194158459146634394 9.969467823087595793179143 Zeros with large index:: >>> besseljzero(0,100); besseljzero(0,1000); besseljzero(0,10000) 313.3742660775278447196902 3140.807295225078628895545 31415.14114171350798533666 >>> besseljzero(5,100); besseljzero(5,1000); besseljzero(5,10000) 321.1893195676003157339222 3148.657306813047523500494 31422.9947255486291798943 >>> besseljzero(0,100,1); besseljzero(0,1000,1); besseljzero(0,10000,1) 311.8018681873704508125112 3139.236339643802482833973 31413.57032947022399485808 Zeros of functions with large order:: >>> besseljzero(50,1) 57.11689916011917411936228 >>> besseljzero(50,2) 62.80769876483536093435393 >>> besseljzero(50,100) 388.6936600656058834640981 >>> besseljzero(50,1,1) 52.99764038731665010944037 >>> besseljzero(50,2,1) 60.02631933279942589882363 >>> besseljzero(50,100,1) 387.1083151608726181086283 Zeros of functions with fractional order:: >>> besseljzero(0.5,1); besseljzero(1.5,1); besseljzero(2.25,4) 3.141592653589793238462643 4.493409457909064175307881 15.15657692957458622921634 Both `J_{\nu}(z)` and `J'_{\nu}(z)` can be expressed as infinite products over their zeros:: >>> v,z = 2, mpf(1) >>> (z/2)**v/gamma(v+1) * \ ... nprod(lambda k: 1-(z/besseljzero(v,k))**2, [1,inf]) ... 0.1149034849319004804696469 >>> besselj(v,z) 0.1149034849319004804696469 >>> (z/2)**(v-1)/2/gamma(v) * \ ... nprod(lambda k: 1-(z/besseljzero(v,k,1))**2, [1,inf]) ... 0.2102436158811325550203884 >>> besselj(v,z,1) 0.2102436158811325550203884 """ return +bessel_zero(ctx, 1, derivative, v, m) @defun def besselyzero(ctx, v, m, derivative=0): r""" For a real order `\nu \ge 0` and a positive integer `m`, returns `y_{\nu,m}`, the `m`-th positive zero of the Bessel function of the second kind `Y_{\nu}(z)` (see :func:`~mpmath.bessely`). Alternatively, with *derivative=1*, gives the first positive zero `y'_{\nu,m}` of `Y'_{\nu}(z)`. The zeros are interlaced according to the inequalities .. math :: y_{\nu,k} < y'_{\nu,k} < y_{\nu,k+1} y_{\nu,1} < y_{\nu+1,2} < y_{\nu,2} < y_{\nu+1,2} < y_{\nu,3} < \cdots **Examples** Initial zeros of the Bessel functions `Y_0(z), Y_1(z), Y_2(z)`:: >>> from sympy.mpmath import * >>> mp.dps = 25; mp.pretty = True >>> besselyzero(0,1); besselyzero(0,2); besselyzero(0,3) 0.8935769662791675215848871 3.957678419314857868375677 7.086051060301772697623625 >>> besselyzero(1,1); besselyzero(1,2); besselyzero(1,3) 2.197141326031017035149034 5.429681040794135132772005 8.596005868331168926429606 >>> besselyzero(2,1); besselyzero(2,2); besselyzero(2,3) 3.384241767149593472701426 6.793807513268267538291167 10.02347797936003797850539 Initial zeros of `Y'_0(z), Y'_1(z), Y'_2(z)`:: >>> besselyzero(0,1,1); besselyzero(0,2,1); besselyzero(0,3,1) 2.197141326031017035149034 5.429681040794135132772005 8.596005868331168926429606 >>> besselyzero(1,1,1); besselyzero(1,2,1); besselyzero(1,3,1) 3.683022856585177699898967 6.941499953654175655751944 10.12340465543661307978775 >>> besselyzero(2,1,1); besselyzero(2,2,1); besselyzero(2,3,1) 5.002582931446063945200176 8.350724701413079526349714 11.57419546521764654624265 Zeros with large index:: >>> besselyzero(0,100); besselyzero(0,1000); besselyzero(0,10000) 311.8034717601871549333419 3139.236498918198006794026 31413.57034538691205229188 >>> besselyzero(5,100); besselyzero(5,1000); besselyzero(5,10000) 319.6183338562782156235062 3147.086508524556404473186 31421.42392920214673402828 >>> besselyzero(0,100,1); besselyzero(0,1000,1); besselyzero(0,10000,1) 313.3726705426359345050449 3140.807136030340213610065 31415.14112579761578220175 Zeros of functions with large order:: >>> besselyzero(50,1) 53.50285882040036394680237 >>> besselyzero(50,2) 60.11244442774058114686022 >>> besselyzero(50,100) 387.1096509824943957706835 >>> besselyzero(50,1,1) 56.96290427516751320063605 >>> besselyzero(50,2,1) 62.74888166945933944036623 >>> besselyzero(50,100,1) 388.6923300548309258355475 Zeros of functions with fractional order:: >>> besselyzero(0.5,1); besselyzero(1.5,1); besselyzero(2.25,4) 1.570796326794896619231322 2.798386045783887136720249 13.56721208770735123376018 """ return +bessel_zero(ctx, 2, derivative, v, m)
{ "repo_name": "Cuuuurzel/KiPyCalc", "path": "sympy/mpmath/functions/bessel.py", "copies": "18", "size": "37942", "license": "mit", "hash": -6605970575510022000, "line_mean": 33.2436823105, "line_max": 100, "alpha_frac": 0.4872700438, "autogenerated": false, "ratio": 2.679141364214094, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0122758750231736, "num_lines": 1108 }
from .functions import defun, defun_wrapped @defun def _jacobi_theta2(ctx, z, q): extra1 = 10 extra2 = 20 # the loops below break when the fixed precision quantities # a and b go to zero; # right shifting small negative numbers by wp one obtains -1, not zero, # so the condition a**2 + b**2 > MIN is used to break the loops. MIN = 2 if z == ctx.zero: if (not ctx._im(q)): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 s = x2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp s += a s = (1 << (wp+1)) + (s << 1) s = ctx.ldexp(s, -wp) else: wp = ctx.prec + extra1 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp-1) are = bre = x2re aim = bim = x2im sre = (1<<wp) + are sim = aim while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp sre += are sim += aim sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) else: if (not ctx._im(q)) and (not ctx._im(z)): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp s = c1 + ((a * cn) >> wp) while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp s += (a * cn) >> wp s = (s << 1) s = ctx.ldexp(s, -wp) s *= ctx.nthroot(q, 4) return s # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp sre = c1 + ((are * cn) >> wp) sim = ((aim * cn) >> wp) while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp sre += ((are * cn) >> wp) sim += ((aim * cn) >> wp) sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) #c2 = (c1*c1 - s1*s1) >> wp c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) #s2 = (c1 * s1) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre = c1re + ((a * cnre) >> wp) sim = c1im + ((a * cnim) >> wp) while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre += ((a * cnre) >> wp) sim += ((a * cnim) >> wp) sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im prec0 = ctx.prec ctx.prec = wp # cos(z), sin(z) with z complex c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 n = 1 termre = c1re termim = c1im sre = c1re + ((are * cnre - aim * cnim) >> wp) sim = c1im + ((are * cnim + aim * cnre) >> wp) n = 3 termre = ((are * cnre - aim * cnim) >> wp) termim = ((are * cnim + aim * cnre) >> wp) sre = c1re + ((are * cnre - aim * cnim) >> wp) sim = c1im + ((are * cnim + aim * cnre) >> wp) n = 5 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 termre = ((are * cnre - aim * cnim) >> wp) termim = ((aim * cnre + are * cnim) >> wp) sre += ((are * cnre - aim * cnim) >> wp) sim += ((aim * cnre + are * cnim) >> wp) n += 2 sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) s *= ctx.nthroot(q, 4) return s @defun def _djacobi_theta2(ctx, z, q, nd): MIN = 2 extra1 = 10 extra2 = 20 if (not ctx._im(q)) and (not ctx._im(z)): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if (nd&1): s = s1 + ((a * sn * 3**nd) >> wp) else: s = c1 + ((a * cn * 3**nd) >> wp) n = 2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if nd&1: s += (a * sn * (2*n+1)**nd) >> wp else: s += (a * cn * (2*n+1)**nd) >> wp n += 1 s = -(s << 1) s = ctx.ldexp(s, -wp) # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if (nd&1): sre = s1 + ((are * sn * 3**nd) >> wp) sim = ((aim * sn * 3**nd) >> wp) else: sre = c1 + ((are * cn * 3**nd) >> wp) sim = ((aim * cn * 3**nd) >> wp) n = 5 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if (nd&1): sre += ((are * sn * n**nd) >> wp) sim += ((aim * sn * n**nd) >> wp) else: sre += ((are * cn * n**nd) >> wp) sim += ((aim * cn * n**nd) >> wp) n += 2 sre = -(sre << 1) sim = -(sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) #c2 = (c1*c1 - s1*s1) >> wp c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) #s2 = (c1 * s1) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre = s1re + ((a * snre * 3**nd) >> wp) sim = s1im + ((a * snim * 3**nd) >> wp) else: sre = c1re + ((a * cnre * 3**nd) >> wp) sim = c1im + ((a * cnim * 3**nd) >> wp) n = 5 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre += ((a * snre * n**nd) >> wp) sim += ((a * snim * n**nd) >> wp) else: sre += ((a * cnre * n**nd) >> wp) sim += ((a * cnim * n**nd) >> wp) n += 2 sre = -(sre << 1) sim = -(sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im prec0 = ctx.prec ctx.prec = wp # cos(2*z), sin(2*z) with z complex c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre = s1re + (((are * snre - aim * snim) * 3**nd) >> wp) sim = s1im + (((are * snim + aim * snre)* 3**nd) >> wp) else: sre = c1re + (((are * cnre - aim * cnim) * 3**nd) >> wp) sim = c1im + (((are * cnim + aim * cnre)* 3**nd) >> wp) n = 5 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre += (((are * snre - aim * snim) * n**nd) >> wp) sim += (((aim * snre + are * snim) * n**nd) >> wp) else: sre += (((are * cnre - aim * cnim) * n**nd) >> wp) sim += (((aim * cnre + are * cnim) * n**nd) >> wp) n += 2 sre = -(sre << 1) sim = -(sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) s *= ctx.nthroot(q, 4) if (nd&1): return (-1)**(nd//2) * s else: return (-1)**(1 + nd//2) * s @defun def _jacobi_theta3(ctx, z, q): extra1 = 10 extra2 = 20 MIN = 2 if z == ctx.zero: if not ctx._im(q): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) s = x a = b = x x2 = (x*x) >> wp while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp s += a s = (1 << wp) + (s << 1) s = ctx.ldexp(s, -wp) return s else: wp = ctx.prec + extra1 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) sre = are = bre = xre sim = aim = bim = xim while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp sre += are sim += aim sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s else: if (not ctx._im(q)) and (not ctx._im(z)): s = 0 wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 s += (a * cn) >> wp while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp s += (a * cn) >> wp s = (1 << wp) + (s << 1) s = ctx.ldexp(s, -wp) return s # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 sre = (are * cn) >> wp sim = (aim * cn) >> wp while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp sre += (are * cn) >> wp sim += (aim * cn) >> wp sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) sre = (a * cnre) >> wp sim = (a * cnim) >> wp while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre += (a * cnre) >> wp sim += (a * cnim) >> wp sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim prec0 = ctx.prec ctx.prec = wp # cos(2*z), sin(2*z) with z complex c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) sre = (are * cnre - aim * cnim) >> wp sim = (aim * cnre + are * cnim) >> wp while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre += (are * cnre - aim * cnim) >> wp sim += (aim * cnre + are * cnim) >> wp sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s @defun def _djacobi_theta3(ctx, z, q, nd): """nd=1,2,3 order of the derivative with respect to z""" MIN = 2 extra1 = 10 extra2 = 20 if (not ctx._im(q)) and (not ctx._im(z)): s = 0 wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 if (nd&1): s += (a * sn) >> wp else: s += (a * cn) >> wp n = 2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp if nd&1: s += (a * sn * n**nd) >> wp else: s += (a * cn * n**nd) >> wp n += 1 s = -(s << (nd+1)) s = ctx.ldexp(s, -wp) # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 if (nd&1): sre = (are * sn) >> wp sim = (aim * sn) >> wp else: sre = (are * cn) >> wp sim = (aim * cn) >> wp n = 2 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp if nd&1: sre += (are * sn * n**nd) >> wp sim += (aim * sn * n**nd) >> wp else: sre += (are * cn * n**nd) >> wp sim += (aim * cn * n**nd) >> wp n += 1 sre = -(sre << (nd+1)) sim = -(sim << (nd+1)) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) if (nd&1): sre = (a * snre) >> wp sim = (a * snim) >> wp else: sre = (a * cnre) >> wp sim = (a * cnim) >> wp n = 2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre += (a * snre * n**nd) >> wp sim += (a * snim * n**nd) >> wp else: sre += (a * cnre * n**nd) >> wp sim += (a * cnim * n**nd) >> wp n += 1 sre = -(sre << (nd+1)) sim = -(sim << (nd+1)) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim prec0 = ctx.prec ctx.prec = wp # cos(2*z), sin(2*z) with z complex c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) if (nd&1): sre = (are * snre - aim * snim) >> wp sim = (aim * snre + are * snim) >> wp else: sre = (are * cnre - aim * cnim) >> wp sim = (aim * cnre + are * cnim) >> wp n = 2 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if(nd&1): sre += ((are * snre - aim * snim) * n**nd) >> wp sim += ((aim * snre + are * snim) * n**nd) >> wp else: sre += ((are * cnre - aim * cnim) * n**nd) >> wp sim += ((aim * cnre + are * cnim) * n**nd) >> wp n += 1 sre = -(sre << (nd+1)) sim = -(sim << (nd+1)) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) if (nd&1): return (-1)**(nd//2) * s else: return (-1)**(1 + nd//2) * s @defun def _jacobi_theta2a(ctx, z, q): """ case ctx._im(z) != 0 theta(2, z, q) = q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=-inf, inf) max term for minimum (2*n+1)*log(q).real - 2* ctx._im(z) n0 = int(ctx._im(z)/log(q).real - 1/2) theta(2, z, q) = q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=n0, inf) + q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n, n0-1, -inf) """ n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2) e2 = ctx.expj(2*z) e = e0 = ctx.expj((2*n+1)*z) a = q**(n*n + n) # leading term term = a * e s = term eps1 = ctx.eps*abs(term) while 1: n += 1 e = e * e2 term = q**(n*n + n) * e if abs(term) < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 term = q**(n*n + n) * e if abs(term) < eps1: break s += term s = s * ctx.nthroot(q, 4) return s @defun def _jacobi_theta3a(ctx, z, q): """ case ctx._im(z) != 0 theta3(z, q) = Sum(q**(n*n) * exp(j*2*n*z), n, -inf, inf) max term for n*abs(log(q).real) + ctx._im(z) ~= 0 n0 = int(- ctx._im(z)/abs(log(q).real)) """ n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) e2 = ctx.expj(2*z) e = e0 = ctx.expj(2*n*z) s = term = q**(n*n) * e eps1 = ctx.eps*abs(term) while 1: n += 1 e = e * e2 term = q**(n*n) * e if abs(term) < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 term = q**(n*n) * e if abs(term) < eps1: break s += term return s @defun def _djacobi_theta2a(ctx, z, q, nd): """ case ctx._im(z) != 0 dtheta(2, z, q, nd) = j* q**1/4 * Sum(q**(n*n + n) * (2*n+1)*exp(j*(2*n + 1)*z), n=-inf, inf) max term for (2*n0+1)*log(q).real - 2* ctx._im(z) ~= 0 n0 = int(ctx._im(z)/log(q).real - 1/2) """ n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2) e2 = ctx.expj(2*z) e = e0 = ctx.expj((2*n + 1)*z) a = q**(n*n + n) # leading term term = (2*n+1)**nd * a * e s = term eps1 = ctx.eps*abs(term) while 1: n += 1 e = e * e2 term = (2*n+1)**nd * q**(n*n + n) * e if abs(term) < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 term = (2*n+1)**nd * q**(n*n + n) * e if abs(term) < eps1: break s += term return ctx.j**nd * s * ctx.nthroot(q, 4) @defun def _djacobi_theta3a(ctx, z, q, nd): """ case ctx._im(z) != 0 djtheta3(z, q, nd) = (2*j)**nd * Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf) max term for minimum n*abs(log(q).real) + ctx._im(z) """ n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) e2 = ctx.expj(2*z) e = e0 = ctx.expj(2*n*z) a = q**(n*n) * e s = term = n**nd * a if n != 0: eps1 = ctx.eps*abs(term) else: eps1 = ctx.eps*abs(a) while 1: n += 1 e = e * e2 a = q**(n*n) * e term = n**nd * a if n != 0: aterm = abs(term) else: aterm = abs(a) if aterm < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 a = q**(n*n) * e term = n**nd * a if n != 0: aterm = abs(term) else: aterm = abs(a) if aterm < eps1: break s += term return (2*ctx.j)**nd * s @defun def jtheta(ctx, n, z, q, derivative=0): if derivative: return ctx._djtheta(n, z, q, derivative) z = ctx.convert(z) q = ctx.convert(q) # Implementation note # If ctx._im(z) is close to zero, _jacobi_theta2 and _jacobi_theta3 # are used, # which compute the series starting from n=0 using fixed precision # numbers; # otherwise _jacobi_theta2a and _jacobi_theta3a are used, which compute # the series starting from n=n0, which is the largest term. # TODO: write _jacobi_theta2a and _jacobi_theta3a using fixed-point if abs(q) > ctx.THETA_Q_LIM: raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM) extra = 10 if z: M = ctx.mag(z) if M > 5 or (n == 1 and M < -5): extra += 2*abs(M) cz = 0.5 extra2 = 50 prec0 = ctx.prec try: ctx.prec += extra if n == 1: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta2(z - ctx.pi/2, q) else: ctx.dps += 10 res = ctx._jacobi_theta2a(z - ctx.pi/2, q) else: res = ctx._jacobi_theta2(z - ctx.pi/2, q) elif n == 2: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta2(z, q) else: ctx.dps += 10 res = ctx._jacobi_theta2a(z, q) else: res = ctx._jacobi_theta2(z, q) elif n == 3: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta3(z, q) else: ctx.dps += 10 res = ctx._jacobi_theta3a(z, q) else: res = ctx._jacobi_theta3(z, q) elif n == 4: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta3(z, -q) else: ctx.dps += 10 res = ctx._jacobi_theta3a(z, -q) else: res = ctx._jacobi_theta3(z, -q) else: raise ValueError finally: ctx.prec = prec0 return res @defun def _djtheta(ctx, n, z, q, derivative=1): z = ctx.convert(z) q = ctx.convert(q) nd = int(derivative) if abs(q) > ctx.THETA_Q_LIM: raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM) extra = 10 + ctx.prec * nd // 10 if z: M = ctx.mag(z) if M > 5 or (n != 1 and M < -5): extra += 2*abs(M) cz = 0.5 extra2 = 50 prec0 = ctx.prec try: ctx.prec += extra if n == 1: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta2a(z - ctx.pi/2, q, nd) else: res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd) elif n == 2: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta2(z, q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta2a(z, q, nd) else: res = ctx._djacobi_theta2(z, q, nd) elif n == 3: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta3(z, q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta3a(z, q, nd) else: res = ctx._djacobi_theta3(z, q, nd) elif n == 4: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta3(z, -q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta3a(z, -q, nd) else: res = ctx._djacobi_theta3(z, -q, nd) else: raise ValueError finally: ctx.prec = prec0 return +res
{ "repo_name": "jamesblunt/sympy", "path": "sympy/mpmath/functions/theta.py", "copies": "51", "size": "37320", "license": "bsd-3-clause", "hash": 1037802819899132500, "line_mean": 34.5767397521, "line_max": 76, "alpha_frac": 0.3867631297, "autogenerated": false, "ratio": 2.7027809965237544, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from functions import defun, defun_wrapped @defun def _jacobi_theta2(ctx, z, q): extra1 = 10 extra2 = 20 # the loops below break when the fixed precision quantities # a and b go to zero; # right shifting small negative numbers by wp one obtains -1, not zero, # so the condition a**2 + b**2 > MIN is used to break the loops. MIN = 2 if z == ctx.zero: if (not ctx._im(q)): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 s = x2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp s += a s = (1 << (wp+1)) + (s << 1) s = ctx.ldexp(s, -wp) else: wp = ctx.prec + extra1 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp-1) are = bre = x2re aim = bim = x2im sre = (1<<wp) + are sim = aim while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp sre += are sim += aim sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) else: if (not ctx._im(q)) and (not ctx._im(z)): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp s = c1 + ((a * cn) >> wp) while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp s += (a * cn) >> wp s = (s << 1) s = ctx.ldexp(s, -wp) s *= ctx.nthroot(q, 4) return s # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp sre = c1 + ((are * cn) >> wp) sim = ((aim * cn) >> wp) while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp sre += ((are * cn) >> wp) sim += ((aim * cn) >> wp) sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) #c2 = (c1*c1 - s1*s1) >> wp c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) #s2 = (c1 * s1) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre = c1re + ((a * cnre) >> wp) sim = c1im + ((a * cnim) >> wp) while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre += ((a * cnre) >> wp) sim += ((a * cnim) >> wp) sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im prec0 = ctx.prec ctx.prec = wp # cos(z), sin(z) with z complex c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 n = 1 termre = c1re termim = c1im sre = c1re + ((are * cnre - aim * cnim) >> wp) sim = c1im + ((are * cnim + aim * cnre) >> wp) n = 3 termre = ((are * cnre - aim * cnim) >> wp) termim = ((are * cnim + aim * cnre) >> wp) sre = c1re + ((are * cnre - aim * cnim) >> wp) sim = c1im + ((are * cnim + aim * cnre) >> wp) n = 5 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 termre = ((are * cnre - aim * cnim) >> wp) termim = ((aim * cnre + are * cnim) >> wp) sre += ((are * cnre - aim * cnim) >> wp) sim += ((aim * cnre + are * cnim) >> wp) n += 2 sre = (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) s *= ctx.nthroot(q, 4) return s @defun def _djacobi_theta2(ctx, z, q, nd): MIN = 2 extra1 = 10 extra2 = 20 if (not ctx._im(q)) and (not ctx._im(z)): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if (nd&1): s = s1 + ((a * sn * 3**nd) >> wp) else: s = c1 + ((a * cn * 3**nd) >> wp) n = 2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if nd&1: s += (a * sn * (2*n+1)**nd) >> wp else: s += (a * cn * (2*n+1)**nd) >> wp n += 1 s = -(s << 1) s = ctx.ldexp(s, -wp) # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im c1, s1 = ctx.cos_sin(ctx._re(z), prec=wp) cn = c1 = ctx.to_fixed(c1, wp) sn = s1 = ctx.to_fixed(s1, wp) c2 = (c1*c1 - s1*s1) >> wp s2 = (c1 * s1) >> (wp - 1) cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if (nd&1): sre = s1 + ((are * sn * 3**nd) >> wp) sim = ((aim * sn * 3**nd) >> wp) else: sre = c1 + ((are * cn * 3**nd) >> wp) sim = ((aim * cn * 3**nd) >> wp) n = 5 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp if (nd&1): sre += ((are * sn * n**nd) >> wp) sim += ((aim * sn * n**nd) >> wp) else: sre += ((are * cn * n**nd) >> wp) sim += ((aim * cn * n**nd) >> wp) n += 2 sre = -(sre << 1) sim = -(sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) x2 = (x*x) >> wp a = b = x2 prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) #c2 = (c1*c1 - s1*s1) >> wp c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) #s2 = (c1 * s1) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) #cn, sn = (cn*c2 - sn*s2) >> wp, (sn*c2 + cn*s2) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre = s1re + ((a * snre * 3**nd) >> wp) sim = s1im + ((a * snim * 3**nd) >> wp) else: sre = c1re + ((a * cnre * 3**nd) >> wp) sim = c1im + ((a * cnim * 3**nd) >> wp) n = 5 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre += ((a * snre * n**nd) >> wp) sim += ((a * snim * n**nd) >> wp) else: sre += ((a * cnre * n**nd) >> wp) sim += ((a * cnim * n**nd) >> wp) n += 2 sre = -(sre << 1) sim = -(sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = x2re aim = bim = x2im prec0 = ctx.prec ctx.prec = wp # cos(2*z), sin(2*z) with z complex c1, s1 = ctx.cos_sin(z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) c2re = (c1re*c1re - c1im*c1im - s1re*s1re + s1im*s1im) >> wp c2im = (c1re*c1im - s1re*s1im) >> (wp - 1) s2re = (c1re*s1re - c1im*s1im) >> (wp - 1) s2im = (c1re*s1im + c1im*s1re) >> (wp - 1) t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre = s1re + (((are * snre - aim * snim) * 3**nd) >> wp) sim = s1im + (((are * snim + aim * snre)* 3**nd) >> wp) else: sre = c1re + (((are * cnre - aim * cnim) * 3**nd) >> wp) sim = c1im + (((are * cnim + aim * cnre)* 3**nd) >> wp) n = 5 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp #cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp t1 = (cnre*c2re - cnim*c2im - snre*s2re + snim*s2im) >> wp t2 = (cnre*c2im + cnim*c2re - snre*s2im - snim*s2re) >> wp t3 = (snre*c2re - snim*c2im + cnre*s2re - cnim*s2im) >> wp t4 = (snre*c2im + snim*c2re + cnre*s2im + cnim*s2re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre += (((are * snre - aim * snim) * n**nd) >> wp) sim += (((aim * snre + are * snim) * n**nd) >> wp) else: sre += (((are * cnre - aim * cnim) * n**nd) >> wp) sim += (((aim * cnre + are * cnim) * n**nd) >> wp) n += 2 sre = -(sre << 1) sim = -(sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) s *= ctx.nthroot(q, 4) if (nd&1): return (-1)**(nd//2) * s else: return (-1)**(1 + nd//2) * s @defun def _jacobi_theta3(ctx, z, q): extra1 = 10 extra2 = 20 MIN = 2 if z == ctx.zero: if not ctx._im(q): wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) s = x a = b = x x2 = (x*x) >> wp while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp s += a s = (1 << wp) + (s << 1) s = ctx.ldexp(s, -wp) return s else: wp = ctx.prec + extra1 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) sre = are = bre = xre sim = aim = bim = xim while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp sre += are sim += aim sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s else: if (not ctx._im(q)) and (not ctx._im(z)): s = 0 wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 s += (a * cn) >> wp while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp s += (a * cn) >> wp s = (1 << wp) + (s << 1) s = ctx.ldexp(s, -wp) return s # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 sre = (are * cn) >> wp sim = (aim * cn) >> wp while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp sre += (are * cn) >> wp sim += (aim * cn) >> wp sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) sre = (a * cnre) >> wp sim = (a * cnim) >> wp while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre += (a * cnre) >> wp sim += (a * cnim) >> wp sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim prec0 = ctx.prec ctx.prec = wp # cos(2*z), sin(2*z) with z complex c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) sre = (are * cnre - aim * cnim) >> wp sim = (aim * cnre + are * cnim) >> wp while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 sre += (are * cnre - aim * cnim) >> wp sim += (aim * cnre + are * cnim) >> wp sre = (1 << wp) + (sre << 1) sim = (sim << 1) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) return s @defun def _djacobi_theta3(ctx, z, q, nd): """nd=1,2,3 order of the derivative with respect to z""" MIN = 2 extra1 = 10 extra2 = 20 if (not ctx._im(q)) and (not ctx._im(z)): s = 0 wp = ctx.prec + extra1 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 if (nd&1): s += (a * sn) >> wp else: s += (a * cn) >> wp n = 2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp if nd&1: s += (a * sn * n**nd) >> wp else: s += (a * cn * n**nd) >> wp n += 1 s = -(s << (nd+1)) s = ctx.ldexp(s, -wp) # case z real, q complex elif not ctx._im(z): wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim c1, s1 = ctx.cos_sin(ctx._re(z)*2, prec=wp) c1 = ctx.to_fixed(c1, wp) s1 = ctx.to_fixed(s1, wp) cn = c1 sn = s1 if (nd&1): sre = (are * sn) >> wp sim = (aim * sn) >> wp else: sre = (are * cn) >> wp sim = (aim * cn) >> wp n = 2 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp cn, sn = (cn*c1 - sn*s1) >> wp, (sn*c1 + cn*s1) >> wp if nd&1: sre += (are * sn * n**nd) >> wp sim += (aim * sn * n**nd) >> wp else: sre += (are * cn * n**nd) >> wp sim += (aim * cn * n**nd) >> wp n += 1 sre = -(sre << (nd+1)) sim = -(sim << (nd+1)) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) #case z complex, q real elif not ctx._im(q): wp = ctx.prec + extra2 x = ctx.to_fixed(ctx._re(q), wp) a = b = x x2 = (x*x) >> wp prec0 = ctx.prec ctx.prec = wp c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) if (nd&1): sre = (a * snre) >> wp sim = (a * snim) >> wp else: sre = (a * cnre) >> wp sim = (a * cnim) >> wp n = 2 while abs(a) > MIN: b = (b*x2) >> wp a = (a*b) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if (nd&1): sre += (a * snre * n**nd) >> wp sim += (a * snim * n**nd) >> wp else: sre += (a * cnre * n**nd) >> wp sim += (a * cnim * n**nd) >> wp n += 1 sre = -(sre << (nd+1)) sim = -(sim << (nd+1)) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) # case z and q complex else: wp = ctx.prec + extra2 xre = ctx.to_fixed(ctx._re(q), wp) xim = ctx.to_fixed(ctx._im(q), wp) x2re = (xre*xre - xim*xim) >> wp x2im = (xre*xim) >> (wp - 1) are = bre = xre aim = bim = xim prec0 = ctx.prec ctx.prec = wp # cos(2*z), sin(2*z) with z complex c1, s1 = ctx.cos_sin(2*z) ctx.prec = prec0 cnre = c1re = ctx.to_fixed(ctx._re(c1), wp) cnim = c1im = ctx.to_fixed(ctx._im(c1), wp) snre = s1re = ctx.to_fixed(ctx._re(s1), wp) snim = s1im = ctx.to_fixed(ctx._im(s1), wp) if (nd&1): sre = (are * snre - aim * snim) >> wp sim = (aim * snre + are * snim) >> wp else: sre = (are * cnre - aim * cnim) >> wp sim = (aim * cnre + are * cnim) >> wp n = 2 while are**2 + aim**2 > MIN: bre, bim = (bre * x2re - bim * x2im) >> wp, \ (bre * x2im + bim * x2re) >> wp are, aim = (are * bre - aim * bim) >> wp, \ (are * bim + aim * bre) >> wp t1 = (cnre*c1re - cnim*c1im - snre*s1re + snim*s1im) >> wp t2 = (cnre*c1im + cnim*c1re - snre*s1im - snim*s1re) >> wp t3 = (snre*c1re - snim*c1im + cnre*s1re - cnim*s1im) >> wp t4 = (snre*c1im + snim*c1re + cnre*s1im + cnim*s1re) >> wp cnre = t1 cnim = t2 snre = t3 snim = t4 if(nd&1): sre += ((are * snre - aim * snim) * n**nd) >> wp sim += ((aim * snre + are * snim) * n**nd) >> wp else: sre += ((are * cnre - aim * cnim) * n**nd) >> wp sim += ((aim * cnre + are * cnim) * n**nd) >> wp n += 1 sre = -(sre << (nd+1)) sim = -(sim << (nd+1)) sre = ctx.ldexp(sre, -wp) sim = ctx.ldexp(sim, -wp) s = ctx.mpc(sre, sim) if (nd&1): return (-1)**(nd//2) * s else: return (-1)**(1 + nd//2) * s @defun def _jacobi_theta2a(ctx, z, q): """ case ctx._im(z) != 0 theta(2, z, q) = q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=-inf, inf) max term for minimum (2*n+1)*log(q).real - 2* ctx._im(z) n0 = int(ctx._im(z)/log(q).real - 1/2) theta(2, z, q) = q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=n0, inf) + q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n, n0-1, -inf) """ n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2) e2 = ctx.expj(2*z) e = e0 = ctx.expj((2*n+1)*z) a = q**(n*n + n) # leading term term = a * e s = term eps1 = ctx.eps*abs(term) while 1: n += 1 e = e * e2 term = q**(n*n + n) * e if abs(term) < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 term = q**(n*n + n) * e if abs(term) < eps1: break s += term s = s * ctx.nthroot(q, 4) return s @defun def _jacobi_theta3a(ctx, z, q): """ case ctx._im(z) != 0 theta3(z, q) = Sum(q**(n*n) * exp(j*2*n*z), n, -inf, inf) max term for n*abs(log(q).real) + ctx._im(z) ~= 0 n0 = int(- ctx._im(z)/abs(log(q).real)) """ n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) e2 = ctx.expj(2*z) e = e0 = ctx.expj(2*n*z) s = term = q**(n*n) * e eps1 = ctx.eps*abs(term) while 1: n += 1 e = e * e2 term = q**(n*n) * e if abs(term) < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 term = q**(n*n) * e if abs(term) < eps1: break s += term return s @defun def _djacobi_theta2a(ctx, z, q, nd): """ case ctx._im(z) != 0 dtheta(2, z, q, nd) = j* q**1/4 * Sum(q**(n*n + n) * (2*n+1)*exp(j*(2*n + 1)*z), n=-inf, inf) max term for (2*n0+1)*log(q).real - 2* ctx._im(z) ~= 0 n0 = int(ctx._im(z)/log(q).real - 1/2) """ n = n0 = int(ctx._im(z)/ctx._re(ctx.log(q)) - 1/2) e2 = ctx.expj(2*z) e = e0 = ctx.expj((2*n + 1)*z) a = q**(n*n + n) # leading term term = (2*n+1)**nd * a * e s = term eps1 = ctx.eps*abs(term) while 1: n += 1 e = e * e2 term = (2*n+1)**nd * q**(n*n + n) * e if abs(term) < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 term = (2*n+1)**nd * q**(n*n + n) * e if abs(term) < eps1: break s += term return ctx.j**nd * s * ctx.nthroot(q, 4) @defun def _djacobi_theta3a(ctx, z, q, nd): """ case ctx._im(z) != 0 djtheta3(z, q, nd) = (2*j)**nd * Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf) max term for minimum n*abs(log(q).real) + ctx._im(z) """ n = n0 = int(-ctx._im(z)/abs(ctx._re(ctx.log(q)))) e2 = ctx.expj(2*z) e = e0 = ctx.expj(2*n*z) a = q**(n*n) * e s = term = n**nd * a if n != 0: eps1 = ctx.eps*abs(term) else: eps1 = ctx.eps*abs(a) while 1: n += 1 e = e * e2 a = q**(n*n) * e term = n**nd * a if n != 0: aterm = abs(term) else: aterm = abs(a) if aterm < eps1: break s += term e = e0 e2 = ctx.expj(-2*z) n = n0 while 1: n -= 1 e = e * e2 a = q**(n*n) * e term = n**nd * a if n != 0: aterm = abs(term) else: aterm = abs(a) if aterm < eps1: break s += term return (2*ctx.j)**nd * s @defun def jtheta(ctx, n, z, q, derivative=0): if derivative: return ctx._djtheta(n, z, q, derivative) z = ctx.convert(z) q = ctx.convert(q) # Implementation note # If ctx._im(z) is close to zero, _jacobi_theta2 and _jacobi_theta3 # are used, # which compute the series starting from n=0 using fixed precision # numbers; # otherwise _jacobi_theta2a and _jacobi_theta3a are used, which compute # the series starting from n=n0, which is the largest term. # TODO: write _jacobi_theta2a and _jacobi_theta3a using fixed-point if abs(q) > ctx.THETA_Q_LIM: raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM) extra = 10 if z: M = ctx.mag(z) if M > 5 or (n == 1 and M < -5): extra += 2*abs(M) cz = 0.5 extra2 = 50 prec0 = ctx.prec try: ctx.prec += extra if n == 1: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta2(z - ctx.pi/2, q) else: ctx.dps += 10 res = ctx._jacobi_theta2a(z - ctx.pi/2, q) else: res = ctx._jacobi_theta2(z - ctx.pi/2, q) elif n == 2: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta2(z, q) else: ctx.dps += 10 res = ctx._jacobi_theta2a(z, q) else: res = ctx._jacobi_theta2(z, q) elif n == 3: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta3(z, q) else: ctx.dps += 10 res = ctx._jacobi_theta3a(z, q) else: res = ctx._jacobi_theta3(z, q) elif n == 4: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._jacobi_theta3(z, -q) else: ctx.dps += 10 res = ctx._jacobi_theta3a(z, -q) else: res = ctx._jacobi_theta3(z, -q) else: raise ValueError finally: ctx.prec = prec0 return res @defun def _djtheta(ctx, n, z, q, derivative=1): z = ctx.convert(z) q = ctx.convert(q) nd = int(derivative) if abs(q) > ctx.THETA_Q_LIM: raise ValueError('abs(q) > THETA_Q_LIM = %f' % ctx.THETA_Q_LIM) extra = 10 + ctx.prec * nd // 10 if z: M = ctx.mag(z) if M > 5 or (n != 1 and M < -5): extra += 2*abs(M) cz = 0.5 extra2 = 50 prec0 = ctx.prec try: ctx.prec += extra if n == 1: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta2a(z - ctx.pi/2, q, nd) else: res = ctx._djacobi_theta2(z - ctx.pi/2, q, nd) elif n == 2: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta2(z, q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta2a(z, q, nd) else: res = ctx._djacobi_theta2(z, q, nd) elif n == 3: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta3(z, q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta3a(z, q, nd) else: res = ctx._djacobi_theta3(z, q, nd) elif n == 4: if ctx._im(z): if abs(ctx._im(z)) < cz * abs(ctx._re(ctx.log(q))): ctx.dps += extra2 res = ctx._djacobi_theta3(z, -q, nd) else: ctx.dps += 10 res = ctx._djacobi_theta3a(z, -q, nd) else: res = ctx._djacobi_theta3(z, -q, nd) else: raise ValueError finally: ctx.prec = prec0 return +res
{ "repo_name": "tarballs-are-good/sympy", "path": "sympy/mpmath/functions/theta.py", "copies": "2", "size": "37319", "license": "bsd-3-clause", "hash": -1568595109849629700, "line_mean": 34.5757864633, "line_max": 76, "alpha_frac": 0.3867734934, "autogenerated": false, "ratio": 2.702904323893677, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40896778172936765, "avg_score": null, "num_lines": null }
from .functions import defun, defun_wrapped @defun def qp(ctx, a, q=None, n=None, **kwargs): r""" Evaluates the q-Pochhammer symbol (or q-rising factorial) .. math :: (a; q)_n = \prod_{k=0}^{n-1} (1-a q^k) where `n = \infty` is permitted if `|q| < 1`. Called with two arguments, ``qp(a,q)`` computes `(a;q)_{\infty}`; with a single argument, ``qp(q)`` computes `(q;q)_{\infty}`. The special case .. math :: \phi(q) = (q; q)_{\infty} = \prod_{k=1}^{\infty} (1-q^k) = \sum_{k=-\infty}^{\infty} (-1)^k q^{(3k^2-k)/2} is also known as the Euler function, or (up to a factor `q^{-1/24}`) the Dedekind eta function. **Examples** If `n` is a positive integer, the function amounts to a finite product:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qp(2,3,5) -725305.0 >>> fprod(1-2*3**k for k in range(5)) -725305.0 >>> qp(2,3,0) 1.0 Complex arguments are allowed:: >>> qp(2-1j, 0.75j) (0.4628842231660149089976379 + 4.481821753552703090628793j) The regular Pochhammer symbol `(a)_n` is obtained in the following limit as `q \to 1`:: >>> a, n = 4, 7 >>> limit(lambda q: qp(q**a,q,n) / (1-q)**n, 1) 604800.0 >>> rf(a,n) 604800.0 The Taylor series of the reciprocal Euler function gives the partition function `P(n)`, i.e. the number of ways of writing `n` as a sum of positive integers:: >>> taylor(lambda q: 1/qp(q), 0, 10) [1.0, 1.0, 2.0, 3.0, 5.0, 7.0, 11.0, 15.0, 22.0, 30.0, 42.0] Special values include:: >>> qp(0) 1.0 >>> findroot(diffun(qp), -0.4) # location of maximum -0.4112484791779547734440257 >>> qp(_) 1.228348867038575112586878 The q-Pochhammer symbol is related to the Jacobi theta functions. For example, the following identity holds:: >>> q = mpf(0.5) # arbitrary >>> qp(q) 0.2887880950866024212788997 >>> root(3,-2)*root(q,-24)*jtheta(2,pi/6,root(q,6)) 0.2887880950866024212788997 """ a = ctx.convert(a) if n is None: n = ctx.inf else: n = ctx.convert(n) assert n >= 0 if q is None: q = a else: q = ctx.convert(q) if n == 0: return ctx.one + 0*(a+q) infinite = (n == ctx.inf) same = (a == q) if infinite: if abs(q) >= 1: if same and (q == -1 or q == 1): return ctx.zero * q raise ValueError("q-function only defined for |q| < 1") elif q == 0: return ctx.one - a maxterms = kwargs.get('maxterms', 50*ctx.prec) if infinite and same: # Euler's pentagonal theorem def terms(): t = 1 yield t k = 1 x1 = q x2 = q**2 while 1: yield (-1)**k * x1 yield (-1)**k * x2 x1 *= q**(3*k+1) x2 *= q**(3*k+2) k += 1 if k > maxterms: raise ctx.NoConvergence return ctx.sum_accurately(terms) # return ctx.nprod(lambda k: 1-a*q**k, [0,n-1]) def factors(): k = 0 r = ctx.one while 1: yield 1 - a*r r *= q k += 1 if k >= n: raise StopIteration if k > maxterms: raise ctx.NoConvergence return ctx.mul_accurately(factors) @defun_wrapped def qgamma(ctx, z, q, **kwargs): r""" Evaluates the q-gamma function .. math :: \Gamma_q(z) = \frac{(q; q)_{\infty}}{(q^z; q)_{\infty}} (1-q)^{1-z}. **Examples** Evaluation for real and complex arguments:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qgamma(4,0.75) 4.046875 >>> qgamma(6,6) 121226245.0 >>> qgamma(3+4j, 0.5j) (0.1663082382255199834630088 + 0.01952474576025952984418217j) The q-gamma function satisfies a functional equation similar to that of the ordinary gamma function:: >>> q = mpf(0.25) >>> z = mpf(2.5) >>> qgamma(z+1,q) 1.428277424823760954685912 >>> (1-q**z)/(1-q)*qgamma(z,q) 1.428277424823760954685912 """ if abs(q) > 1: return ctx.qgamma(z,1/q)*q**((z-2)*(z-1)*0.5) return ctx.qp(q, q, None, **kwargs) / \ ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z) @defun_wrapped def qfac(ctx, z, q, **kwargs): r""" Evaluates the q-factorial, .. math :: [n]_q! = (1+q)(1+q+q^2)\cdots(1+q+\cdots+q^{n-1}) or more generally .. math :: [z]_q! = \frac{(q;q)_z}{(1-q)^z}. **Examples** >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qfac(0,0) 1.0 >>> qfac(4,3) 2080.0 >>> qfac(5,6) 121226245.0 >>> qfac(1+1j, 2+1j) (0.4370556551322672478613695 + 0.2609739839216039203708921j) """ if ctx.isint(z) and ctx._re(z) > 0: n = int(ctx._re(z)) return ctx.qp(q, q, n, **kwargs) / (1-q)**n return ctx.qgamma(z+1, q, **kwargs) @defun def qhyper(ctx, a_s, b_s, q, z, **kwargs): r""" Evaluates the basic hypergeometric series or hypergeometric q-series .. math :: \,_r\phi_s \left[\begin{matrix} a_1 & a_2 & \ldots & a_r \\ b_1 & b_2 & \ldots & b_s \end{matrix} ; q,z \right] = \sum_{n=0}^\infty \frac{(a_1;q)_n, \ldots, (a_r;q)_n} {(b_1;q)_n, \ldots, (b_s;q)_n} \left((-1)^n q^{n\choose 2}\right)^{1+s-r} \frac{z^n}{(q;q)_n} where `(a;q)_n` denotes the q-Pochhammer symbol (see :func:`~mpmath.qp`). **Examples** Evaluation works for real and complex arguments:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qhyper([0.5], [2.25], 0.25, 4) -0.1975849091263356009534385 >>> qhyper([0.5], [2.25], 0.25-0.25j, 4) (2.806330244925716649839237 + 3.568997623337943121769938j) >>> qhyper([1+j], [2,3+0.5j], 0.25, 3+4j) (9.112885171773400017270226 - 1.272756997166375050700388j) Comparing with a summation of the defining series, using :func:`~mpmath.nsum`:: >>> b, q, z = 3, 0.25, 0.5 >>> qhyper([], [b], q, z) 0.6221136748254495583228324 >>> nsum(lambda n: z**n / qp(q,q,n)/qp(b,q,n) * q**(n*(n-1)), [0,inf]) 0.6221136748254495583228324 """ #a_s = [ctx._convert_param(a)[0] for a in a_s] #b_s = [ctx._convert_param(b)[0] for b in b_s] #q = ctx._convert_param(q)[0] a_s = [ctx.convert(a) for a in a_s] b_s = [ctx.convert(b) for b in b_s] q = ctx.convert(q) z = ctx.convert(z) r = len(a_s) s = len(b_s) d = 1+s-r maxterms = kwargs.get('maxterms', 50*ctx.prec) def terms(): t = ctx.one yield t qk = 1 k = 0 x = 1 while 1: for a in a_s: p = 1 - a*qk t *= p for b in b_s: p = 1 - b*qk if not p: raise ValueError t /= p t *= z x *= (-1)**d * qk ** d qk *= q t /= (1 - qk) k += 1 yield t * x if k > maxterms: raise ctx.NoConvergence return ctx.sum_accurately(terms)
{ "repo_name": "tectronics/mpmath", "path": "mpmath/functions/qfunctions.py", "copies": "6", "size": "7603", "license": "bsd-3-clause", "hash": -5684427589036143000, "line_mean": 26.2508960573, "line_max": 78, "alpha_frac": 0.4803367092, "autogenerated": false, "ratio": 2.8284970238095237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0023886350706470998, "num_lines": 279 }
from functions import defun, defun_wrapped @defun def qp(ctx, a, q=None, n=None, **kwargs): r""" Evaluates the q-Pochhammer symbol (or q-rising factorial) .. math :: (a; q)_n = \prod_{k=0}^{n-1} (1-a q^k) where `n = \infty` is permitted if `|q| < 1`. Called with two arguments, ``qp(a,q)`` computes `(a;q)_{\infty}`; with a single argument, ``qp(q)`` computes `(q;q)_{\infty}`. The special case .. math :: \phi(q) = (q; q)_{\infty} = \prod_{k=1}^{\infty} (1-q^k) = \sum_{k=-\infty}^{\infty} (-1)^k q^{(3k^2-k)/2} is also known as the Euler function, or (up to a factor `q^{-1/24}`) the Dirichlet eta function. **Examples** If `n` is a positive integer, the function amounts to a finite product:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qp(2,3,5) -725305.0 >>> fprod(1-2*3**k for k in range(5)) -725305.0 >>> qp(2,3,0) 1.0 Complex arguments are allowed:: >>> qp(2-1j, 0.75j) (0.4628842231660149089976379 + 4.481821753552703090628793j) The regular Pochhammer symbol `(a)_n` is obtained in the following limit as `q \to 1`:: >>> a, n = 4, 7 >>> limit(lambda q: qp(q**a,q,n) / (1-q)**n, 1) 604800.0 >>> rf(a,n) 604800.0 The Taylor series of the reciprocal Euler function gives the partition function `P(n)`, i.e. the number of ways of writing `n` as a sum of positive integers:: >>> taylor(lambda q: 1/qp(q), 0, 10) [1.0, 1.0, 2.0, 3.0, 5.0, 7.0, 11.0, 15.0, 22.0, 30.0, 42.0] Special values include:: >>> qp(0) 1.0 >>> findroot(diffun(qp), -0.4) # location of maximum -0.4112484791779547734440257 >>> qp(_) 1.228348867038575112586878 The q-Pochhammer symbol is related to the Jacobi theta functions. For example, the following identity holds:: >>> q = mpf(0.5) # arbitrary >>> qp(q) 0.2887880950866024212788997 >>> root(3,-2)*root(q,-24)*jtheta(2,pi/6,root(q,6)) 0.2887880950866024212788997 """ a = ctx.convert(a) if n is None: n = ctx.inf else: n = ctx.convert(n) assert n >= 0 if q is None: q = a else: q = ctx.convert(q) if n == 0: return ctx.one + 0*(a+q) infinite = (n == ctx.inf) same = (a == q) if infinite: if abs(q) >= 1: if same and (q == -1 or q == 1): return ctx.zero * q raise ValueError("q-function only defined for |q| < 1") elif q == 0: return ctx.one - a maxterms = kwargs.get('maxterms', 50*ctx.prec) if infinite and same: # Euler's pentagonal theorem def terms(): t = 1 yield t k = 1 x1 = q x2 = q**2 while 1: yield (-1)**k * x1 yield (-1)**k * x2 x1 *= q**(3*k+1) x2 *= q**(3*k+2) k += 1 if k > maxterms: raise ctx.NoConvergence return ctx.sum_accurately(terms) # return ctx.nprod(lambda k: 1-a*q**k, [0,n-1]) def factors(): k = 0 r = ctx.one while 1: yield 1 - a*r r *= q k += 1 if k >= n: raise StopIteration if k > maxterms: raise ctx.NoConvergence return ctx.mul_accurately(factors) @defun_wrapped def qgamma(ctx, z, q, **kwargs): r""" Evaluates the q-gamma function .. math :: \Gamma_q(z) = \frac{(q; q)_{\infty}}{(q^z; q)_{\infty}} (1-q)^{1-z}. **Examples** Evaluation for real and complex arguments:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qgamma(4,0.75) 4.046875 >>> qgamma(6,6) 121226245.0 >>> qgamma(3+4j, 0.5j) (0.1663082382255199834630088 + 0.01952474576025952984418217j) The q-gamma function satisfies a functional equation similar to that of the ordinary gamma function:: >>> q = mpf(0.25) >>> z = mpf(2.5) >>> qgamma(z+1,q) 1.428277424823760954685912 >>> (1-q**z)/(1-q)*qgamma(z,q) 1.428277424823760954685912 """ if abs(q) > 1: return ctx.qgamma(z,1/q)*q**((z-2)*(z-1)*0.5) return ctx.qp(q, q, None, **kwargs) / \ ctx.qp(q**z, q, None, **kwargs) * (1-q)**(1-z) @defun_wrapped def qfac(ctx, z, q, **kwargs): r""" Evaluates the q-factorial, .. math :: [n]_q! = (1+q)(1+q+q^2)\cdots(1+q+\cdots+q^{n-1}) or more generally .. math :: [z]_q! = \frac{(q;q)_z}{(1-q)^z}. **Examples** >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qfac(0,0) 1.0 >>> qfac(4,3) 2080.0 >>> qfac(5,6) 121226245.0 >>> qfac(1+1j, 2+1j) (0.4370556551322672478613695 + 0.2609739839216039203708921j) """ if ctx.isint(z) and ctx._re(z) > 0: n = int(ctx._re(z)) return ctx.qp(q, q, n, **kwargs) / (1-q)**n return ctx.qgamma(z+1, q, **kwargs) @defun def qhyper(ctx, a_s, b_s, q, z, **kwargs): r""" Evaluates the basic hypergeometric series or hypergeometric q-series .. math :: \,_r\phi_s \left[\begin{matrix} a_1 & a_2 & \ldots & a_r \\ b_1 & b_2 & \ldots & b_s \end{matrix} ; q,z \right] = \sum_{n=0}^\infty \frac{(a_1;q)_n, \ldots, (a_r;q)_n} {(b_1;q)_n, \ldots, (b_s;q)_n} \left((-1)^n q^{n\choose 2}\right)^{1+s-r} \frac{z^n}{(q;q)_n} where `(a;q)_n` denotes the q-Pochhammer symbol (see :func:`~mpmath.qp`). **Examples** Evaluation works for real and complex arguments:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> qhyper([0.5], [2.25], 0.25, 4) -0.1975849091263356009534385 >>> qhyper([0.5], [2.25], 0.25-0.25j, 4) (2.806330244925716649839237 + 3.568997623337943121769938j) >>> qhyper([1+j], [2,3+0.5j], 0.25, 3+4j) (9.112885171773400017270226 - 1.272756997166375050700388j) Comparing with a summation of the defining series, using :func:`~mpmath.nsum`:: >>> b, q, z = 3, 0.25, 0.5 >>> qhyper([], [b], q, z) 0.6221136748254495583228324 >>> nsum(lambda n: z**n / qp(q,q,n)/qp(b,q,n) * q**(n*(n-1)), [0,inf]) 0.6221136748254495583228324 """ #a_s = [ctx._convert_param(a)[0] for a in a_s] #b_s = [ctx._convert_param(b)[0] for b in b_s] #q = ctx._convert_param(q)[0] a_s = map(ctx.convert, a_s) b_s = map(ctx.convert, b_s) q = ctx.convert(q) z = ctx.convert(z) r = len(a_s) s = len(b_s) d = 1+s-r maxterms = kwargs.get('maxterms', 50*ctx.prec) def terms(): t = ctx.one yield t qk = 1 k = 0 x = 1 while 1: for a in a_s: p = 1 - a*qk t *= p for b in b_s: p = 1 - b*qk if not p: raise ValueError t /= p t *= z x *= (-1)**d * qk ** d qk *= q t /= (1 - qk) k += 1 yield t * x if k > maxterms: raise ctx.NoConvergence return ctx.sum_accurately(terms)
{ "repo_name": "pernici/sympy", "path": "sympy/mpmath/functions/qfunctions.py", "copies": "3", "size": "7585", "license": "bsd-3-clause", "hash": 1031899442854489100, "line_mean": 26.1863799283, "line_max": 78, "alpha_frac": 0.4805537245, "autogenerated": false, "ratio": 2.832337565347274, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4812891289847274, "avg_score": null, "num_lines": null }
from .functions import defun, defun_wrapped @defun_wrapped def _erf_complex(ctx, z): z2 = ctx.square_exp_arg(z, -1) #z2 = -z**2 v = (2/ctx.sqrt(ctx.pi))*z * ctx.hyp1f1((1,2),(3,2), z2) if not ctx._re(z): v = ctx._im(v)*ctx.j return v @defun_wrapped def _erfc_complex(ctx, z): if ctx.re(z) > 2: z2 = ctx.square_exp_arg(z) nz2 = ctx.fneg(z2, exact=True) v = ctx.exp(nz2)/ctx.sqrt(ctx.pi) * ctx.hyperu((1,2),(1,2), z2) else: v = 1 - ctx._erf_complex(z) if not ctx._re(z): v = 1+ctx._im(v)*ctx.j return v @defun def erf(ctx, z): z = ctx.convert(z) if ctx._is_real_type(z): try: return ctx._erf(z) except NotImplementedError: pass if ctx._is_complex_type(z) and not z.imag: try: return type(z)(ctx._erf(z.real)) except NotImplementedError: pass return ctx._erf_complex(z) @defun def erfc(ctx, z): z = ctx.convert(z) if ctx._is_real_type(z): try: return ctx._erfc(z) except NotImplementedError: pass if ctx._is_complex_type(z) and not z.imag: try: return type(z)(ctx._erfc(z.real)) except NotImplementedError: pass return ctx._erfc_complex(z) @defun def square_exp_arg(ctx, z, mult=1, reciprocal=False): prec = ctx.prec*4+20 if reciprocal: z2 = ctx.fmul(z, z, prec=prec) z2 = ctx.fdiv(ctx.one, z2, prec=prec) else: z2 = ctx.fmul(z, z, prec=prec) if mult != 1: z2 = ctx.fmul(z2, mult, exact=True) return z2 @defun_wrapped def erfi(ctx, z): if not z: return z z2 = ctx.square_exp_arg(z) v = (2/ctx.sqrt(ctx.pi)*z) * ctx.hyp1f1((1,2), (3,2), z2) if not ctx._re(z): v = ctx._im(v)*ctx.j return v @defun_wrapped def erfinv(ctx, x): xre = ctx._re(x) if (xre != x) or (xre < -1) or (xre > 1): return ctx.bad_domain("erfinv(x) is defined only for -1 <= x <= 1") x = xre #if ctx.isnan(x): return x if not x: return x if x == 1: return ctx.inf if x == -1: return ctx.ninf if abs(x) < 0.9: a = 0.53728*x**3 + 0.813198*x else: # An asymptotic formula u = ctx.ln(2/ctx.pi/(abs(x)-1)**2) a = ctx.sign(x) * ctx.sqrt(u - ctx.ln(u))/ctx.sqrt(2) ctx.prec += 10 return ctx.findroot(lambda t: ctx.erf(t)-x, a) @defun_wrapped def npdf(ctx, x, mu=0, sigma=1): sigma = ctx.convert(sigma) return ctx.exp(-(x-mu)**2/(2*sigma**2)) / (sigma*ctx.sqrt(2*ctx.pi)) @defun_wrapped def ncdf(ctx, x, mu=0, sigma=1): a = (x-mu)/(sigma*ctx.sqrt(2)) if a < 0: return ctx.erfc(-a)/2 else: return (1+ctx.erf(a))/2 @defun_wrapped def betainc(ctx, a, b, x1=0, x2=1, regularized=False): if x1 == x2: v = 0 elif not x1: if x1 == 0 and x2 == 1: v = ctx.beta(a, b) else: v = x2**a * ctx.hyp2f1(a, 1-b, a+1, x2) / a else: m, d = ctx.nint_distance(a) if m <= 0: if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 a += h elif d < -4: ctx.prec -= d s1 = x2**a * ctx.hyp2f1(a,1-b,a+1,x2) s2 = x1**a * ctx.hyp2f1(a,1-b,a+1,x1) v = (s1 - s2) / a if regularized: v /= ctx.beta(a,b) return v @defun def gammainc(ctx, z, a=0, b=None, regularized=False): regularized = bool(regularized) z = ctx.convert(z) if a is None: a = ctx.zero lower_modified = False else: a = ctx.convert(a) lower_modified = a != ctx.zero if b is None: b = ctx.inf upper_modified = False else: b = ctx.convert(b) upper_modified = b != ctx.inf # Complete gamma function if not (upper_modified or lower_modified): if regularized: if ctx.re(z) < 0: return ctx.inf elif ctx.re(z) > 0: return ctx.one else: return ctx.nan return ctx.gamma(z) if a == b: return ctx.zero # Standardize if ctx.re(a) > ctx.re(b): return -ctx.gammainc(z, b, a, regularized) # Generalized gamma if upper_modified and lower_modified: return +ctx._gamma3(z, a, b, regularized) # Upper gamma elif lower_modified: return ctx._upper_gamma(z, a, regularized) # Lower gamma elif upper_modified: return ctx._lower_gamma(z, b, regularized) @defun def _lower_gamma(ctx, z, b, regularized=False): # Pole if ctx.isnpint(z): return type(z)(ctx.inf) G = [z] * regularized negb = ctx.fneg(b, exact=True) def h(z): T1 = [ctx.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b return (T1,) return ctx.hypercomb(h, [z]) @defun def _upper_gamma(ctx, z, a, regularized=False): # Fast integer case, when available if ctx.isint(z): try: if regularized: # Gamma pole if ctx.isnpint(z): return type(z)(ctx.zero) orig = ctx.prec try: ctx.prec += 10 return ctx._gamma_upper_int(z, a) / ctx.gamma(z) finally: ctx.prec = orig else: return ctx._gamma_upper_int(z, a) except NotImplementedError: pass nega = ctx.fneg(a, exact=True) G = [z] * regularized # Use 2F0 series when possible; fall back to lower gamma representation try: def h(z): r = z-1 return [([ctx.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] return ctx.hypercomb(h, [z], force_series=True) except ctx.NoConvergence: def h(z): T1 = [], [1, z-1], [z], G, [], [], 0 T2 = [-ctx.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a return T1, T2 return ctx.hypercomb(h, [z]) @defun def _gamma3(ctx, z, a, b, regularized=False): pole = ctx.isnpint(z) if regularized and pole: return ctx.zero try: ctx.prec += 15 # We don't know in advance whether it's better to write as a difference # of lower or upper gamma functions, so try both T1 = ctx.gammainc(z, a, regularized=regularized) T2 = ctx.gammainc(z, b, regularized=regularized) R = T1 - T2 if ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: return R if not pole: T1 = ctx.gammainc(z, 0, b, regularized=regularized) T2 = ctx.gammainc(z, 0, a, regularized=regularized) R = T1 - T2 # May be ok, but should probably at least print a warning # about possible cancellation if 1: #ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: return R finally: ctx.prec -= 15 raise NotImplementedError @defun_wrapped def expint(ctx, n, z): if ctx.isint(n) and ctx._is_real_type(z): try: return ctx._expint_int(n, z) except NotImplementedError: pass if ctx.isnan(n) or ctx.isnan(z): return z*n if z == ctx.inf: return 1/z if z == 0: # integral from 1 to infinity of t^n if ctx.re(n) <= 1: # TODO: reasonable sign of infinity return type(z)(ctx.inf) else: return ctx.one/(n-1) if n == 0: return ctx.exp(-z)/z if n == -1: return ctx.exp(-z)*(z+1)/z**2 return z**(n-1) * ctx.gammainc(1-n, z) @defun_wrapped def li(ctx, z, offset=False): if offset: if z == 2: return ctx.zero return ctx.ei(ctx.ln(z)) - ctx.ei(ctx.ln2) if not z: return z if z == 1: return ctx.ninf return ctx.ei(ctx.ln(z)) @defun def ei(ctx, z): try: return ctx._ei(z) except NotImplementedError: return ctx._ei_generic(z) @defun_wrapped def _ei_generic(ctx, z): # Note: the following is currently untested because mp and fp # both use special-case ei code if z == ctx.inf: return z if z == ctx.ninf: return ctx.zero if ctx.mag(z) > 1: try: r = ctx.one/z v = ctx.exp(z)*ctx.hyper([1,1],[],r, maxterms=ctx.prec, force_series=True)/z im = ctx._im(z) if im > 0: v += ctx.pi*ctx.j if im < 0: v -= ctx.pi*ctx.j return v except ctx.NoConvergence: pass v = z*ctx.hyp2f2(1,1,2,2,z) + ctx.euler if ctx._im(z): v += 0.5*(ctx.log(z) - ctx.log(ctx.one/z)) else: v += ctx.log(abs(z)) return v @defun def e1(ctx, z): try: return ctx._e1(z) except NotImplementedError: return ctx.expint(1, z) @defun def ci(ctx, z): try: return ctx._ci(z) except NotImplementedError: return ctx._ci_generic(z) @defun_wrapped def _ci_generic(ctx, z): if ctx.isinf(z): if z == ctx.inf: return ctx.zero if z == ctx.ninf: return ctx.pi*1j jz = ctx.fmul(ctx.j,z,exact=True) njz = ctx.fneg(jz,exact=True) v = 0.5*(ctx.ei(jz) + ctx.ei(njz)) zreal = ctx._re(z) zimag = ctx._im(z) if zreal == 0: if zimag > 0: v += ctx.pi*0.5j if zimag < 0: v -= ctx.pi*0.5j if zreal < 0: if zimag >= 0: v += ctx.pi*1j if zimag < 0: v -= ctx.pi*1j if ctx._is_real_type(z) and zreal > 0: v = ctx._re(v) return v @defun def si(ctx, z): try: return ctx._si(z) except NotImplementedError: return ctx._si_generic(z) @defun_wrapped def _si_generic(ctx, z): if ctx.isinf(z): if z == ctx.inf: return 0.5*ctx.pi if z == ctx.ninf: return -0.5*ctx.pi # Suffers from cancellation near 0 if ctx.mag(z) >= -1: jz = ctx.fmul(ctx.j,z,exact=True) njz = ctx.fneg(jz,exact=True) v = (-0.5j)*(ctx.ei(jz) - ctx.ei(njz)) zreal = ctx._re(z) if zreal > 0: v -= 0.5*ctx.pi if zreal < 0: v += 0.5*ctx.pi if ctx._is_real_type(z): v = ctx._re(v) return v else: return z*ctx.hyp1f2((1,2),(3,2),(3,2),-0.25*z*z) @defun_wrapped def chi(ctx, z): nz = ctx.fneg(z, exact=True) v = 0.5*(ctx.ei(z) + ctx.ei(nz)) zreal = ctx._re(z) zimag = ctx._im(z) if zimag > 0: v += ctx.pi*0.5j elif zimag < 0: v -= ctx.pi*0.5j elif zreal < 0: v += ctx.pi*1j return v @defun_wrapped def shi(ctx, z): # Suffers from cancellation near 0 if ctx.mag(z) >= -1: nz = ctx.fneg(z, exact=True) v = 0.5*(ctx.ei(z) - ctx.ei(nz)) zimag = ctx._im(z) if zimag > 0: v -= 0.5j*ctx.pi if zimag < 0: v += 0.5j*ctx.pi return v else: return z * ctx.hyp1f2((1,2),(3,2),(3,2),0.25*z*z) @defun_wrapped def fresnels(ctx, z): if z == ctx.inf: return ctx.mpf(0.5) if z == ctx.ninf: return ctx.mpf(-0.5) return ctx.pi*z**3/6*ctx.hyp1f2((3,4),(3,2),(7,4),-ctx.pi**2*z**4/16) @defun_wrapped def fresnelc(ctx, z): if z == ctx.inf: return ctx.mpf(0.5) if z == ctx.ninf: return ctx.mpf(-0.5) return z*ctx.hyp1f2((1,4),(1,2),(5,4),-ctx.pi**2*z**4/16)
{ "repo_name": "shipci/sympy", "path": "sympy/mpmath/functions/expintegrals.py", "copies": "47", "size": "11452", "license": "bsd-3-clause", "hash": 752051106462992500, "line_mean": 26.2666666667, "line_max": 79, "alpha_frac": 0.5060251484, "autogenerated": false, "ratio": 2.814450724993856, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from functions import defun, defun_wrapped @defun_wrapped def _erf_complex(ctx, z): z2 = ctx.square_exp_arg(z, -1) #z2 = -z**2 v = (2/ctx.sqrt(ctx.pi))*z * ctx.hyp1f1((1,2),(3,2), z2) if not ctx._re(z): v = ctx._im(v)*ctx.j return v @defun_wrapped def _erfc_complex(ctx, z): if ctx.re(z) > 2: z2 = ctx.square_exp_arg(z) nz2 = ctx.fneg(z2, exact=True) v = ctx.exp(nz2)/ctx.sqrt(ctx.pi) * ctx.hyperu((1,2),(1,2), z2) else: v = 1 - ctx._erf_complex(z) if not ctx._re(z): v = 1+ctx._im(v)*ctx.j return v @defun def erf(ctx, z): z = ctx.convert(z) if ctx._is_real_type(z): try: return ctx._erf(z) except NotImplementedError: pass if ctx._is_complex_type(z) and not z.imag: try: return type(z)(ctx._erf(z.real)) except NotImplementedError: pass return ctx._erf_complex(z) @defun def erfc(ctx, z): z = ctx.convert(z) if ctx._is_real_type(z): try: return ctx._erfc(z) except NotImplementedError: pass if ctx._is_complex_type(z) and not z.imag: try: return type(z)(ctx._erfc(z.real)) except NotImplementedError: pass return ctx._erfc_complex(z) @defun def square_exp_arg(ctx, z, mult=1, reciprocal=False): prec = ctx.prec*4+20 if reciprocal: z2 = ctx.fmul(z, z, prec=prec) z2 = ctx.fdiv(ctx.one, z2, prec=prec) else: z2 = ctx.fmul(z, z, prec=prec) if mult != 1: z2 = ctx.fmul(z2, mult, exact=True) return z2 @defun_wrapped def erfi(ctx, z): if not z: return z z2 = ctx.square_exp_arg(z) v = (2/ctx.sqrt(ctx.pi)*z) * ctx.hyp1f1((1,2), (3,2), z2) if not ctx._re(z): v = ctx._im(v)*ctx.j return v @defun_wrapped def erfinv(ctx, x): xre = ctx._re(x) if (xre != x) or (xre < -1) or (xre > 1): return ctx.bad_domain("erfinv(x) is defined only for -1 <= x <= 1") x = xre #if ctx.isnan(x): return x if not x: return x if x == 1: return ctx.inf if x == -1: return ctx.ninf if abs(x) < 0.9: a = 0.53728*x**3 + 0.813198*x else: # An asymptotic formula u = ctx.ln(2/ctx.pi/(abs(x)-1)**2) a = ctx.sign(x) * ctx.sqrt(u - ctx.ln(u))/ctx.sqrt(2) ctx.prec += 10 return ctx.findroot(lambda t: ctx.erf(t)-x, a) @defun_wrapped def npdf(ctx, x, mu=0, sigma=1): sigma = ctx.convert(sigma) return ctx.exp(-(x-mu)**2/(2*sigma**2)) / (sigma*ctx.sqrt(2*ctx.pi)) @defun_wrapped def ncdf(ctx, x, mu=0, sigma=1): a = (x-mu)/(sigma*ctx.sqrt(2)) if a < 0: return ctx.erfc(-a)/2 else: return (1+ctx.erf(a))/2 @defun_wrapped def betainc(ctx, a, b, x1=0, x2=1, regularized=False): if x1 == x2: v = 0 elif not x1: if x1 == 0 and x2 == 1: v = ctx.beta(a, b) else: v = x2**a * ctx.hyp2f1(a, 1-b, a+1, x2) / a else: m, d = ctx.nint_distance(a) if m <= 0: if d < -ctx.prec: h = +ctx.eps ctx.prec *= 2 a += h elif d < -4: ctx.prec -= d s1 = x2**a * ctx.hyp2f1(a,1-b,a+1,x2) s2 = x1**a * ctx.hyp2f1(a,1-b,a+1,x1) v = (s1 - s2) / a if regularized: v /= ctx.beta(a,b) return v @defun def gammainc(ctx, z, a=0, b=None, regularized=False): regularized = bool(regularized) z = ctx.convert(z) if a is None: a = ctx.zero lower_modified = False else: a = ctx.convert(a) lower_modified = a != ctx.zero if b is None: b = ctx.inf upper_modified = False else: b = ctx.convert(b) upper_modified = b != ctx.inf # Complete gamma function if not (upper_modified or lower_modified): if regularized: if ctx.re(z) < 0: return ctx.inf elif ctx.re(z) > 0: return ctx.one else: return ctx.nan return ctx.gamma(z) if a == b: return ctx.zero # Standardize if ctx.re(a) > ctx.re(b): return -ctx.gammainc(z, b, a, regularized) # Generalized gamma if upper_modified and lower_modified: return +ctx._gamma3(z, a, b, regularized) # Upper gamma elif lower_modified: return ctx._upper_gamma(z, a, regularized) # Lower gamma elif upper_modified: return ctx._lower_gamma(z, b, regularized) @defun def _lower_gamma(ctx, z, b, regularized=False): # Pole if ctx.isnpint(z): return type(z)(ctx.inf) G = [z] * regularized negb = ctx.fneg(b, exact=True) def h(z): T1 = [ctx.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b return (T1,) return ctx.hypercomb(h, [z]) @defun def _upper_gamma(ctx, z, a, regularized=False): # Fast integer case, when available if ctx.isint(z): try: if regularized: # Gamma pole if ctx.isnpint(z): return type(z)(ctx.zero) orig = ctx.prec try: ctx.prec += 10 return ctx._gamma_upper_int(z, a) / ctx.gamma(z) finally: ctx.prec = orig else: return ctx._gamma_upper_int(z, a) except NotImplementedError: pass nega = ctx.fneg(a, exact=True) G = [z] * regularized # Use 2F0 series when possible; fall back to lower gamma representation try: def h(z): r = z-1 return [([ctx.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] return ctx.hypercomb(h, [z], force_series=True) except ctx.NoConvergence: def h(z): T1 = [], [1, z-1], [z], G, [], [], 0 T2 = [-ctx.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a return T1, T2 return ctx.hypercomb(h, [z]) @defun def _gamma3(ctx, z, a, b, regularized=False): pole = ctx.isnpint(z) if regularized and pole: return ctx.zero try: ctx.prec += 15 # We don't know in advance whether it's better to write as a difference # of lower or upper gamma functions, so try both T1 = ctx.gammainc(z, a, regularized=regularized) T2 = ctx.gammainc(z, b, regularized=regularized) R = T1 - T2 if ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: return R if not pole: T1 = ctx.gammainc(z, 0, b, regularized=regularized) T2 = ctx.gammainc(z, 0, a, regularized=regularized) R = T1 - T2 # May be ok, but should probably at least print a warning # about possible cancellation if 1: #ctx.mag(R) - max(ctx.mag(T1), ctx.mag(T2)) > -10: return R finally: ctx.prec -= 15 raise NotImplementedError @defun_wrapped def expint(ctx, n, z): if ctx.isint(n) and ctx._is_real_type(z): try: return ctx._expint_int(n, z) except NotImplementedError: pass if ctx.isnan(n) or ctx.isnan(z): return z*n if z == ctx.inf: return 1/z if z == 0: # integral from 1 to infinity of t^n if ctx.re(n) <= 1: # TODO: reasonable sign of infinity return type(z)(ctx.inf) else: return ctx.one/(n-1) if n == 0: return ctx.exp(-z)/z if n == -1: return ctx.exp(-z)*(z+1)/z**2 return z**(n-1) * ctx.gammainc(1-n, z) @defun_wrapped def li(ctx, z, offset=False): if offset: if z == 2: return ctx.zero return ctx.ei(ctx.ln(z)) - ctx.ei(ctx.ln2) if not z: return z if z == 1: return ctx.ninf return ctx.ei(ctx.ln(z)) @defun def ei(ctx, z): try: return ctx._ei(z) except NotImplementedError: return ctx._ei_generic(z) @defun_wrapped def _ei_generic(ctx, z): # Note: the following is currently untested because mp and fp # both use special-case ei code if z == ctx.inf: return z if z == ctx.ninf: return ctx.zero if ctx.mag(z) > 1: try: r = ctx.one/z v = ctx.exp(z)*ctx.hyper([1,1],[],r, maxterms=ctx.prec, force_series=True)/z im = ctx._im(z) if im > 0: v += ctx.pi*ctx.j if im < 0: v -= ctx.pi*ctx.j return v except ctx.NoConvergence: pass v = z*ctx.hyp2f2(1,1,2,2,z) + ctx.euler if ctx._im(z): v += 0.5*(ctx.log(z) - ctx.log(ctx.one/z)) else: v += ctx.log(abs(z)) return v @defun def e1(ctx, z): try: return ctx._e1(z) except NotImplementedError: return ctx.expint(1, z) @defun def ci(ctx, z): try: return ctx._ci(z) except NotImplementedError: return ctx._ci_generic(z) @defun_wrapped def _ci_generic(ctx, z): if ctx.isinf(z): if z == ctx.inf: return ctx.zero if z == ctx.ninf: return ctx.pi*1j jz = ctx.fmul(ctx.j,z,exact=True) njz = ctx.fneg(jz,exact=True) v = 0.5*(ctx.ei(jz) + ctx.ei(njz)) zreal = ctx._re(z) zimag = ctx._im(z) if zreal == 0: if zimag > 0: v += ctx.pi*0.5j if zimag < 0: v -= ctx.pi*0.5j if zreal < 0: if zimag >= 0: v += ctx.pi*1j if zimag < 0: v -= ctx.pi*1j if ctx._is_real_type(z) and zreal > 0: v = ctx._re(v) return v @defun def si(ctx, z): try: return ctx._si(z) except NotImplementedError: return ctx._si_generic(z) @defun_wrapped def _si_generic(ctx, z): if ctx.isinf(z): if z == ctx.inf: return 0.5*ctx.pi if z == ctx.ninf: return -0.5*ctx.pi # Suffers from cancellation near 0 if ctx.mag(z) >= -1: jz = ctx.fmul(ctx.j,z,exact=True) njz = ctx.fneg(jz,exact=True) v = (-0.5j)*(ctx.ei(jz) - ctx.ei(njz)) zreal = ctx._re(z) if zreal > 0: v -= 0.5*ctx.pi if zreal < 0: v += 0.5*ctx.pi if ctx._is_real_type(z): v = ctx._re(v) return v else: return z*ctx.hyp1f2((1,2),(3,2),(3,2),-0.25*z*z) @defun_wrapped def chi(ctx, z): nz = ctx.fneg(z, exact=True) v = 0.5*(ctx.ei(z) + ctx.ei(nz)) zreal = ctx._re(z) zimag = ctx._im(z) if zimag > 0: v += ctx.pi*0.5j elif zimag < 0: v -= ctx.pi*0.5j elif zreal < 0: v += ctx.pi*1j return v @defun_wrapped def shi(ctx, z): # Suffers from cancellation near 0 if ctx.mag(z) >= -1: nz = ctx.fneg(z, exact=True) v = 0.5*(ctx.ei(z) - ctx.ei(nz)) zimag = ctx._im(z) if zimag > 0: v -= 0.5j*ctx.pi if zimag < 0: v += 0.5j*ctx.pi return v else: return z * ctx.hyp1f2((1,2),(3,2),(3,2),0.25*z*z) @defun_wrapped def fresnels(ctx, z): if z == ctx.inf: return ctx.mpf(0.5) if z == ctx.ninf: return ctx.mpf(-0.5) return ctx.pi*z**3/6*ctx.hyp1f2((3,4),(3,2),(7,4),-ctx.pi**2*z**4/16) @defun_wrapped def fresnelc(ctx, z): if z == ctx.inf: return ctx.mpf(0.5) if z == ctx.ninf: return ctx.mpf(-0.5) return z*ctx.hyp1f2((1,4),(1,2),(5,4),-ctx.pi**2*z**4/16)
{ "repo_name": "tarballs-are-good/sympy", "path": "sympy/mpmath/functions/expintegrals.py", "copies": "2", "size": "11451", "license": "bsd-3-clause", "hash": 4167985780781838300, "line_mean": 26.2642857143, "line_max": 79, "alpha_frac": 0.5060693389, "autogenerated": false, "ratio": 2.8148967551622417, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4320966094062242, "avg_score": null, "num_lines": null }
from functions import gcd, continuedFraction import math def properFraction(pNume,pDeno): '''pNume: numerator, pDeno: Denominator return [z,x,y] such that pNume/pDeno =z + x/y and gcd(x,y) = 1''' t = gcd(pDeno,pNume) z = pNume / pDeno x,y = (pNume - z*pDeno)/t, pDeno/t return [z,x,y] print properFraction(20,15) print continuedFraction(13,10) def fractionPeriod(pN): '''return the period of continued Fraction of squareRoot(n)''' squareRoot = int(math.floor(math.sqrt(pN))) length = 10 *squareRoot l = continuedFraction(pN, length)[1:] # print l k = 0 nonSatisfy = True while nonSatisfy: k+=1 nonSatisfy = False for t in range(0,10): if (t+2)* k < length: if not nonSatisfy and l[t*k:(t+1)*k]!= l[(t+1)*k:(t+2)*k]: # print l[t*k:(t+1)*k], l[(t+1)*k:(t+2)*k] nonSatisfy = True return k print fractionPeriod(7) def test(): A = [2,3,5,6,7,8,10,11,12,13] for a in A: print a,fractionPeriod(a) # test() def main(): limit = 10000 count = 0 for n in range(2,limit): t = int(math.sqrt(n)) if t * t != n: period = fractionPeriod(n) if period % 2 == 1: print n,period count +=1 print 'count', count main()
{ "repo_name": "nguyenkims/projecteuler-python", "path": "src/p64.py", "copies": "1", "size": "1193", "license": "mit", "hash": 2668366855950331400, "line_mean": 20.3035714286, "line_max": 67, "alpha_frac": 0.6202849958, "autogenerated": false, "ratio": 2.312015503875969, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.34323004996759693, "avg_score": null, "num_lines": null }
from functions import get_dist from components import * class Task(object): def __init__(self): self._children = [] def run(self): pass def add_child(self, c): self._children.append(c) class Selector(Task): def __init__(self): super().__init__() def run(self): for c in self._children: if c.run(): return True return False class Sequence(Task): def __init__(self): super().__init__() def run(self): for c in self._children: if not c.run(): return False return True class HasTarget(Task): def __init__(self, owner, world): super().__init__() self.o = owner self.w = world def run(self): if getattr(self.o, "attacktarget"): return True # elif getattr(self.o, "autoattacktarget"): # return True else: return False class FindTarget(Task): def __init__(self, owner, world): super().__init__() self.o = owner self.w = world def run(self): if not getattr(self.o, "searchingtarget"): self.o.searchingtarget = SearchingTarget() class AITargetInRange(Task): def __init__(self, owner, world): super().__init__() self.o = owner self.w = world def run(self): if getattr(self.o, "attacktarget"): t = self.o.attacktarget.who d = get_dist( t.position.x, t.position.y, self.o.position.x, self.o.position.y ) if d <= 32: return True else: if getattr(self.o, "autoattacktarget"): delattr(self.o, "autoattacktarget") class AIAttackTarget(Task): def __init__(self, owner, world): super().__init__() self.o = owner self.w = world def run(self): if getattr(self.o, "attacktarget"): t = self.o.attacktarget.who if getattr(t, "hp"): if t.hp.value > 0: self.o.autoattacktarget = AutoAttackTarget(target=t) return True else: delattr(self.o, "attacktarget") if getattr(self.o, "autoattacktarget"): delattr(self.o, "autoattacktarget") return True class AIMoveToTarget(Task): def __init__(self, owner, world): super().__init__() self.o = owner self.w = world def run(self): if getattr(self.o, "attacktarget"): t = self.o.attacktarget.who if not getattr(self.o, "followtarget"): self.o.followtarget = FollowTarget() self.o.followtarget.who = t self.o.followtarget.range = 24 return False class AICheckTargetDead(Task): def __init__(self, owner, world): super().__init__() self.o = owner self.w = world def run(self): if getattr(self.o, "attacktarget"): if getattr(self.o.attacktarget.who, "hp"): if self.o.attacktarget.who.hp.value <= 0: delattr(self.o, "attacktarget") if getattr(self.o, "followtarget"): delattr(self.o, "followtarget") if getattr(self.o, "autoattacktarget"): delattr(self.o, "autoattacktarget") return True class Inverter(Task): def __init__(self, t): super().__init__() self.add_child(t) def run(self): for c in self._children: return not c.run() class BehaviorTree: def __init__(self): self.root = None def run(self): return self.root.run() class KillPlayer(BehaviorTree): def __init__(self, owner, world): super().__init__() o, w = owner, world root = Sequence() # invert = Inverter() targ_seq = Sequence() hastarget = HasTarget(o, w) findtarget = FindTarget(o, w) gettarget = Selector() gettarget.add_child(hastarget) gettarget.add_child(findtarget) checkrange = Inverter(AITargetInRange(o, w)) move_to = AIMoveToTarget(o, w) closeenough = Sequence() closeenough.add_child(checkrange) closeenough.add_child(move_to) targ_seq.add_child(gettarget) targ_seq.add_child(closeenough) root.add_child(targ_seq) self.root = root
{ "repo_name": "NiclasEriksen/rpg_procgen", "path": "ai_components.py", "copies": "1", "size": "4591", "license": "cc0-1.0", "hash": 1916995935734421200, "line_mean": 24.087431694, "line_max": 72, "alpha_frac": 0.5129601394, "autogenerated": false, "ratio": 3.947549441100602, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49605095805006016, "avg_score": null, "num_lines": null }
from .functions import get_models_from_string, quick_search, \ get_object_from_string from django import forms from django.contrib.contenttypes.models import ContentType from django.http import Http404, HttpResponse, HttpResponseServerError from django.utils import simplejson, simplejson as json from django.utils.datastructures import MultiValueDictKeyError from what_apps.do.models import \ TaskPrototype #Ideally, instead of importing this here, we'll have an autocomplete class that lives in do.functions. import itertools def submit_generic(request, app_name, object_type): Model=ContentType.objects.get(app_label=app_name, model=object_type.lower()).model_class() class GenericForm(forms.ModelForm): class Meta: model = Model form=GenericForm(request.POST) #Start populating a dict to return. response_dict = {'errors': []} #Start with an empty list of errors. if form.is_valid(): form.save() response_dict['success'] = True else: response_dict['success'] = False for error in form.errors: response_dict['errors'].append(error) #Append to the list only if there are errors, otherwise this will remain an empty list #Whether or not the form was valid, we'll return a json dict with the bool for success and a list of errors (which will obviously be blank if there are none) return HttpResponse(simplejson.dumps(response_dict)) def submit_generic_partial(request, object_type, object_id): try: model=ContentType.objects.get(model=object_type).model_class() except: model=ContentType.objects.get(model=object_type.lower()).model_class() object = model.objects.get(id=object_id) object.__dict__.update(request.POST) #Lots of objects have descriptions and then get a little fudgy with unicode. #TODO: Find a better way to do this. try: object.description = str(request.POST['description']) except MultiValueDictKeyError: pass object.save() return HttpResponse(1) #TODO: Turn this into a generic ajax form #One interesting challenge will be to determine if the user has security to submit the form in question #ie, let's say that the form rendered on the page (for an anon) is some LowLevel form that anons are allowed to submit. #However, if the anon changes the flag to the name of a HighLevel form, we'll then need to check to make sure they are cool #We could modify the save methods by permission and that will clear the whole thing up. That will take some discipline! #Example: #def submitGenericAjax(request): # form_type=SomeMethodForDeterminingTheNameOfTheForm(request.POST['form_type']) # # if not user.has_perm_to_handle_form_type(form_type): # raise a 403 # # form=form_type(request.POST) # # # #....and so on def autocomplete_dispatcher(request): return admin_autocomplete(request) ''' Dubious and deprecated code to follow. TODO: Make this more generic and find it a good home. This is potential useful code for getting more than simply the name of the object to be autocompleted against. with_description = request.GET['with_description'] #1 or 0 depending on whether or not we need this autocomplete to return the description. We're trusting that nobody is going to use this on a model that lacks a description field. if request.GET['lookup_type'] == "task_family": #We want to get the entire task family, including the progeny of the task. search_phrase=request.GET['term'] #What is our search phrase? #We don't need to think about models here, we know we're dealing with TaskPrototype. task_prototypes = TaskPrototype.objects.filter(name__icontains = search_phrase) products = [] for tp in task_prototypes: #Iterate through the potential parents label = str(tp.name) result_meta = str(tp._meta) #Get the app and model for the result, ie auth.user result_id = str(tp.id) #Get the ID for the result. elephant = result_meta + "_" + result_id #Now we have "auth.user_34" or something tp_children_dict = {} #Start an empty dict for this TaskPrototype's children for progeny in tp.children.all(): #Iterate through the progeny objects for this TaskPrototype's children tp_children_dict[progeny.child.id] = progeny.child.name #With the child's ID as the key, set it's name to the value product_dict = dict(elephant = elephant, label = label, xhr = label, children = tp_children_dict) products.append(product_dict) return HttpResponse(json.dumps(products)) ''' def autocomplete_with_description(request): ''' autocompletes for a model that has a description field and returns the name, description, and ID. ''' search_phrase=request.GET['term'] #What is our search phrase? models = get_models_from_string(request.GET['criterion']) query = itertools.chain() for model in models: search = quick_search(search_phrase, model, 'name') #TODO: How will we go about un-hardcoding name? query = itertools.chain(query, search) products = [] for result in query: label = str(result) #TODO: Again, bad. result_meta = str(result._meta) #Get the app and model for the result, ie auth.user result_id = str(result.id) #Get the ID for the result. elephant = result_meta + "_" + result_id #Now we have "auth.user_34" or something try: description = result.description except AttributeError: description = "This model doesn't have a description." product_dict = dict(elephant = elephant, label = label, xhr = label, description=description) products.append(product_dict) return HttpResponse(json.dumps(products)) def admin_autocomplete(request): search_phrase=request.GET['term'] #What is our search phrase? models = get_models_from_string(request.GET['criterion']) query = itertools.chain() for model, property_list in models: #Each item in models will be a list where the first item is a model, the second a list of field names in that model against which we'll search. search = quick_search(search_phrase, model, property_list) #TODO: How will we go about un-hardcoding name? query = itertools.chain(query, search) # try: # fields = [] # fields.append(model_info.split('__')[1]) # for field in fields: # kwargs = {'%s__%s' % (field, 'ngram'): search_phrase} # search = SearchQuerySet().filter(**kwargs).models(model) # query = itertools.chain(query, search) # except IndexError: #TODO: Goodness, this is dreadful. We need to be able to autocomplete against things besides 'name' #search = model.objects.filter(name__icontains = search_phrase) #Make the searches iterable products = [] for result in query: label = str(result) #TODO: Again, bad. result_meta = str(result._meta) #Get the app and model for the result, ie auth.user result_id = str(result.id) #Get the ID for the result. elephant = result_meta + "_" + result_id #Now we have "auth.user_34" or something product_dict = dict(elephant = elephant, label = label, xhr = label) products.append(product_dict) return HttpResponse(json.dumps(products)) def save_tags_for_object(request, model_info): ''' Tags model app name, mdoel name, and ID, and saves tags from a django-taggit formatted tag string. ''' #We can probably seperate this out into its own function object = get_object_from_string(model_info) object.tags.set(request.POST['tags']) return HttpResponse(1)
{ "repo_name": "SlashRoot/WHAT", "path": "what_apps/utility/views.py", "copies": "1", "size": "8364", "license": "mit", "hash": -8299788858504212000, "line_mean": 40.6169154229, "line_max": 235, "alpha_frac": 0.6409612626, "autogenerated": false, "ratio": 4.169491525423729, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.04708136391588986, "num_lines": 201 }
from .functions import group_by, take, first from .count_unanswered_tickets import count_unanswered_tickets from .count_open_tickets import count_open_tickets from .get_shifts import get_shifts from .get_printers import group_printer_errors def format_printer_errors(printers): printer_count = 8 string = '' for error, printer_list in printers.items(): string += error + '\\n' string += ', '.join([p['name'] for p in take(printer_count, printer_list)]) string += '\\n\\n' if len(string) is 0: return 'No Problems' return string def get_first_shift(shifts): grouped = group_by(lambda s: s['start_time'], shifts) s = sorted(grouped.items(), key=lambda k: k[0]) if s: # the first shift, and the shifts, not the time. return s[0][1] return [] def collect(): unanswered_ticket_count = count_unanswered_tickets() open_ticket_count = count_open_tickets() printers = group_printer_errors() shifts = get_shifts() now_on_helpdesk = [s['name'] for s in shifts['now'] if s['location'] == 'Helpdesk'] now_on_tcar = [s['name'] for s in shifts['now'] if s['location'] == 'TCAR'] next_on_helpdesk = get_first_shift([s for s in shifts['later'] if s['location'] == 'Helpdesk']) next_on_tcar = get_first_shift([s for s in shifts['later'] if s['location'] == 'TCAR']) next_helpdesk_names = [s['name'] for s in next_on_helpdesk] next_tcar_names = [s['name'] for s in next_on_tcar] next_helpdesk_time = first(next_on_helpdesk, {}).get('time', '') next_tcar_time = first(next_on_tcar, {}).get('time', '') # print(next_on_tcar, first(next_on_tcar, {})) return { 'printers': format_printer_errors(printers), 'now_helpdesk_name': '\\n'.join(now_on_helpdesk) or 'No one is currently scheduled', 'now_tcar_name': '\\n'.join(now_on_tcar) or 'No one is currently scheduled', 'next_helpdesk_time': next_helpdesk_time, 'next_helpdesk_name': '\\n'.join(next_helpdesk_names) or 'No more shifts scheduled', 'next_tcar_time': next_tcar_time, 'next_tcar_name': '\\n'.join(next_tcar_names) or 'No more shifts scheduled', 'open_tickets': open_ticket_count, 'unanswered_tickets': unanswered_ticket_count, }
{ "repo_name": "hawkrives/stolaf-ubersicht-widgets", "path": "lib/collect_data.py", "copies": "1", "size": "2297", "license": "mit", "hash": 95951145313974350, "line_mean": 36.6557377049, "line_max": 99, "alpha_frac": 0.6286460601, "autogenerated": false, "ratio": 3.120923913043478, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9236796250335179, "avg_score": 0.0025547445616598058, "num_lines": 61 }
from functions import inch_to_mm from functions import sta_value import os import win32com.client class CarmOmf(object): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name): self.carm_part_number = carm_part_number self.order_of_new_product = order_of_new_product self.instance_id = instance_id self.copy_from_product = copy_from_product self.cfp_name = cfp_name self.catia = win32com.client.Dispatch('catia.application') #path_doc = open('path_default.txt', 'r') #lib_path_unedited = path_doc.readline() #lib_path = lib_path_unedited.replace('\n', '') #path_doc.close() #lib_path = os.path.dirname(os.path.abspath(__file__)) + '\LIBRARY' lib_path = os.getcwd() + '\LIBRARY' self.path = lib_path self.side = side self.extention = '\\seed_carm_' + side + '.CATPart' self.oFileSys = self.catia.FileSystem self.productDocument1 = self.catia.ActiveDocument self.documents = self.catia.Documents def add_carm_as_external_component(self): """Instantiates CARM from external library""" product1 = self.productDocument1.Product collection_irms = product1.Products product_to_insert_carm = collection_irms.Item(self.order_of_new_product) children_of_product_to_insert_carm = product_to_insert_carm.Products PartDocPath = self.path + self.extention print PartDocPath PartDocPath1 = self.path + '\CA' + self.carm_part_number + '.CATPart' self.oFileSys.CopyFile(PartDocPath, PartDocPath1, True) PartDoc = self.catia.Documents.NewFrom(PartDocPath1) PartDoc1 = PartDoc.Product PartDoc1.PartNumber = 'CA' + self.carm_part_number print PartDoc1.Name NewComponent = children_of_product_to_insert_carm.AddExternalComponent(PartDoc) PartDoc.Close() self.oFileSys.DeleteFile(PartDocPath1) print self.instance_id NewComponent.Name = self.instance_id print NewComponent.Name print 'EXT COMP ADDED' self.catia.ActiveWindow.ActiveViewer.Reframe() def change_inst_id(self): Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) Product2 = to_p.ReferenceProduct carm_name = to_p.Name carm_name1 = carm_name.replace('_INSTL', '') carm_name2 = carm_name1 + '_CARM' Product2Products = Product2.Products product_forpaste = Product2Products.Item(3) product_forpaste.Name = carm_name2 print product_forpaste.Name def access_carm(self): """Returns self carm_part""" carm_document = self.documents.Item('CA' + self.carm_part_number + '.CATPart') carm_part = carm_document.Part return carm_part def ZZZ_access_annotations(self): carm_part = self.access_carm() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations for ann in xrange(1, anns.Count+1): ann1 = anns.Item(ann) ann1text = ann1.Text() ann1text_2d = ann1text.Get2dAnnot() ann1text_value = ann1text_2d.Text print ann1text_value def modif_ref_annotation(self, size): carm_part = self.access_carm() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations ref_annotation = anns.Item(1) ann1text = ref_annotation.Text() ann1text_2d = ann1text.Get2dAnnot() ann1text_value = size + 'IN OUTBD FRNG SUPPORT REF' ann1text_2d.Text = ann1text_value print ann1text_value ref_annotation.ModifyVisu() def modif_sta_annotation(self, sta_values_fake): carm_part = self.access_carm() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations sta_annotation = anns.Item(2) ann1text = sta_annotation.Text() ann1text_2d = ann1text.Get2dAnnot() sta = sta_values_fake[self.copy_from_product - 5] # ann1text_value = 'STA ' + sta + '\nLBL 74.3\nWL 294.8\nREF' ann1text_value = 'STA ' + sta + '\nREF' ann1text_2d.Text = ann1text_value print ann1text_value sta_annotation.ModifyVisu() def select_current_product(self): # ICM_1.ApplyWorkMode(2) product1 = self.productDocument1.Product products1 = product1.Products for prod in xrange(1, 5): product_to_replace = products1.Item(prod) products_to_replace = product_to_replace.Products for det in xrange(1, products_to_replace.Count+1): product_act_to_replace_nonc = products_to_replace.Item(det) if self.cfp_name in str(product_act_to_replace_nonc.Name): return product_act_to_replace_nonc else: continue for prod in xrange(5, products1.Count+1): product_to_replace = products1.Item(prod) if self.cfp_name in str(product_to_replace.Name): return product_to_replace else: continue def select_carm_to_paste_data(self): """Returns part of the CARM through the reference product""" Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) Product2 = to_p.ReferenceProduct Product2Products = Product2.Products product_forpaste = Product2Products.Item(Product2Products.Count) print product_forpaste.name Part3 = product_forpaste.ReferenceProduct PartDocument3 = Part3.Parent print PartDocument3.name geom_elem3 = PartDocument3.Part return geom_elem3 def ZZZ_add_geosets(self): """Adds Reference Geometry geometrical set""" carm_part = self.access_carm() geosets = carm_part.HybridBodies new_geoset = geosets.add() new_geoset.name = 'Reference Geometry1' first_gs = geosets.Item(1) first_gs.name = 'Renamed' # for reference: For IdxSet = 1 To AnnotationSets.Count def ZZZ_get_points(self, jd_number): ref_connecter = [] carm_part = self.access_carm() geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') print geoset1.name geosets1 = geoset1.HybridBodies print 'Joint Definition ' + str(jd_number) geoset2 = geosets1.Item('Joint Definition ' + jd_number) print geoset2.name points = geoset2.HybridShapes for point in xrange(1, points.Count+1): target = points.Item(point) if not 'FIDV' in target.Name: ref_connecter.append(target.Name) else: continue print ref_connecter return ref_connecter # print ref_connecter.Name # ref_connecter_coordinates_X = ref_connecter.X # ref_connecter_coordinates_Y = ref_connecter.Y # ref_connecter_coordinates_Z = ref_connecter.Z # ref_connecter_new_coordinates.append(ref_connecter_coordinates_X.Value) # ref_connecter_new_coordinates.append(ref_connecter_coordinates_Y.Value) # ref_connecter_new_coordinates.append(ref_connecter_coordinates_Z.Value) # print ref_connecter_new_coordinates # ref_connecter_new_coordinates[0] += 300.0 # print ref_connecter_new_coordinates # ref_connecter.SetCoordinates(ref_connecter_new_coordinates) def set_parameters(self, sta_value_pairs, size): carm_part = self.select_carm_to_paste_data() parameters1 = carm_part.Parameters ref_param = parameters1.Item('ref_connector_X') sta_param = parameters1.Item('sta_connector_X') # direct_param = parameters1.Item('view_direction_connector_X') print ref_param.Value print sta_param.Value coord_to_move = sta_value_pairs[self.copy_from_product - 5] print coord_to_move ref_param.Value = coord_to_move + (inch_to_mm(float(size))) - inch_to_mm(0.25) sta_param.Value = coord_to_move + inch_to_mm(0.25) # direct_param.Value = coord_to_move + (Inch_to_mm(float(size)/2)) + Inch_to_mm(7.0) print ref_param.Value print sta_param.Value def set_standard_parts_params(self, jd_number): carm_part = self.select_carm_to_paste_data() hole_qty = 0 parameters1 = carm_part.Parameters # for param1 in xrange(1, parameters1.Count): # param2 = parameters1.Item(param1) # print param2.Name selection1 = self.productDocument1.Selection selection1.Clear() hybridBodies1 = carm_part.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) HybridShapes1 = hybridBody2.HybridShapes for shape in xrange(HybridShapes1.Count): hole_qty += 1 print hole_qty param_hole_qty = parameters1.Item('Joint Definitions\Joint Definition 0' + str(jd_number) + '\Hole Quantity') param_hole_qty.Value = str(hole_qty) if jd_number == 1: param = parameters1.Item('FCM10F5CPS05WH') param.Value = str(hole_qty) + '|FCM10F5CPS05WH | 302 CRES, Passivated, with Captive Washer, Head Color' elif jd_number == 2: param = parameters1.Item('BACS12FA3K3') param.Value = str(hole_qty) + '|BACS12FA3K3 | SCREW, WASHER HEAD, CROSS RECESS, FULL THREADED, 6AL-4V TITANIUM' def copy_bodies_and_paste(self, fastener): """Makes copy of fasteners solids and pastes them to the current CARM""" selection1 = self.productDocument1.Selection selection1.Clear() product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('(Name = ' + fastener + '*REF-Name = *.*), sel')) # selection1.Search(str('Name = ' + fastener + '*REF, sel')) try: selection1.Copy() except: pass else: selection2 = self.productDocument1.Selection selection2.Clear() part2 = self.select_carm_to_paste_data() selection2.Add(part2) selection2.PasteSpecial('CATPrtResultWithOutLink') part2.Update() def rename_part_body(self): """renames part body and activates it""" carm = self.access_carm() bodies = carm.Bodies part_body = bodies.Item(1) part_body.name = 'CA' + self.carm_part_number carm.InWorkObject = part_body def copy_ref_surface_and_paste(self, size): """Makes copy of reference geometry geoset and pastes to current CARM""" selection1 = self.productDocument1.Selection selection1.Clear() product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('Name = *' + size + '*IN*REF, sel')) selection1.Copy() selection2 = self.productDocument1.Selection selection2.Clear() geoset3 = self.select_carm_to_paste_data() hybridBodies1 = geoset3.HybridBodies hybridBody1 = hybridBodies1.Item("Reference Geometry") selection2.Add(hybridBody1) # selection2.visProperties.SetShow(0) selection2.PasteSpecial('CATPrtResultWithOutLink') geoset3.Update() # change visual properties selection3 = self.productDocument1.Selection selection3.Clear() geoset4 = self.select_carm_to_paste_data() selection3.Add(geoset4) selection3.Search('Name = Reference Geometry, sel') selection3.visProperties.SetRealColor(210, 180, 140, 0) selection3.visProperties.SetRealOpacity(255, 0) def copy_jd2_bacs12fa3k3_and_paste(self, size, arch, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() product1 = self.select_current_product() selection1.Add(product1) if type_of_geometry == 'points': if arch: selection1.Search(str('(Name = ' + size + '*FAIRING*PLENUM*ARCH*-Name = *CENTERLINE*), sel')) else: selection1.Search(str('(Name = ' + size + '*FAIRING*PLENUM*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) selection1.Copy() self.paste_to_jd(2) else: if arch: selection1.Search(str('(Name = ' + size + '*FAIRING*PLENUM*ARCH*-Name = *CENTERLINE*), sel')) else: selection1.Search(str('(Name = ' + size + '*FAIRING*PLENUM*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def ZZZ_rename_vectors(self, jd_number): part2 = self.select_carm_to_paste_data() hybridBodies1 = part2.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) hybridShapes1 = hybridBody2.HybridShapes for Plenum_spud in range(1, hybridShapes1.Count + 1): Vector= hybridShapes1.Item(Plenum_spud) if 'CENTERLINE' in Vector.name: Vector.name = 'FIDV_01' else: continue def create_jd_vectors(self, jd_number): part1 = self.select_carm_to_paste_data() hybridBodies1 = part1.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) hybridShapes1 = hybridBody2.HybridShapes hybridShapePointCenter1 = hybridShapes1.Item(1) reference1 = part1.CreateReferenceFromObject(hybridShapePointCenter1) hybridShapeFactory1 = part1.HybridShapeFactory hybridBody3 = hybridBodies1.Item("Construction Geometry (REF)") hybridBodies3 = hybridBody3.HybridBodies hybridBody4 = hybridBodies3.Item("Misc Construction Geometry") hybridShapes2 = hybridBody4.HybridShapes hybridShapePlaneOffset1 = hybridShapes2.Item('jd' + str(jd_number) + '_vector_direction') reference2 = part1.CreateReferenceFromObject(hybridShapePlaneOffset1) hybridShapeDirection1 = hybridShapeFactory1.AddNewDirection(reference2) hybridShapeLinePtDir1 = hybridShapeFactory1.AddNewLinePtDir(reference1, hybridShapeDirection1, 0.000000, 25.400000, True) hybridBody2.AppendHybridShape(hybridShapeLinePtDir1) hybridShapeLinePtDir1.Name = 'FIDV_0' + str(jd_number) part1.Update() def copy_jd1_fcm10f5cps05wh_and_paste(self, size, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() product1 = self.select_current_product() selection1.Add(product1) if type_of_geometry == 'points': selection1.Search(str('(Name = ' + size + '*FAIRING*LIGHT*-Name = *CENTERLINE*), sel')) selection1.Copy() self.paste_to_jd(1) else: selection1.Search(str('(Name = ' + size + '*FAIRING*LIGHT*-Name = *CENTERLINE*), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def activate_view(self, jd_number): carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) TPSViews = ann_set1.TPSViews view_to_activate = TPSViews.Item(int(jd_number) + 3) #annotationFactory1 = ann_set1.AnnotationFactory ann_set1.ActiveView = view_to_activate # annotationFactory1.ActivateTPSView(ann_set1, view_to_activate) def add_jd_annotation(self, jd_number, sta_value_pairs, size, side, capture_number): """Adds JOINT DEFINITION XX annotation""" annot_text = 'JOINT DEFINITION ' + jd_number carm_part = self.access_carm() KBE = carm_part.GetCustomerFactory("BOEAnntFactory") self.activate_view(jd_number) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Joint Definition ' + jd_number) points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(1)) userSurface1 = userSurfaces1.Generate(reference1) for point in xrange(2, points.Count): reference2 = carm_part.CreateReferenceFromObject(points.Item(point)) print reference2.name userSurface1.AddReference(reference2) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] if jd_number == '01': y = inch_to_mm(12) z = 0 if side == 'LH': k = 1 else: k = -1 # addition = k*(Inch_to_mm(float(size)/2)) addition = k*(inch_to_mm(12.0)) else: y = inch_to_mm(19) z = 0 if side == 'LH': k = -1 else: k = 1 # addition = k*(Inch_to_mm(float(size)/2)) addition = k*(inch_to_mm(12.0)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 16) captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) self.rename_part_body() KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.hide_last_annotation() carm_part.Update() # self.activate_top_prod() def ZZZ_manage_annotations_visibility(self): part1 = self.select_carm_to_paste_data() part1_annotation_set1 = part1.AnnotationSets annotation_set1 = part1_annotation_set1.Item(1) captures1 = annotation_set1.Captures engineering_def_release = captures1.Item(2) engineering_def_release_annotations1 = engineering_def_release.Annotations engineering_def_release_annotation1 = engineering_def_release_annotations1.Item(1) print engineering_def_release_annotation1.Name engineering_def_release_annotation1.visProperties.SetShow(0) part1.Update() def hide_last_annotation(self): selection1 = self.productDocument1.Selection selection1.Clear() carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations sta_annotation = anns.Item(anns.Count) selection1.Add(sta_annotation) selection1.visProperties.SetShow(1) carm_part.Update() def ZZZ_unhide_std_parts_bodies(self): selection1 = self.productDocument1.Selection selection1.Clear() carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets std_bodies = carm_part.Bodies ann_set1 = ann_sets.Item(1) captures1 = ann_set1.Captures # for capture in xrange(1, captures1.Count+1): # self.access_captures(capture) capture1 = captures1.Item(3) capture1.DisplayCapture() for body in xrange(1, std_bodies.Count+1): body1 = std_bodies.Item(body) selection1.Add(body1) selection1.visProperties.SetShow(0) carm_part.Update() def ZZZ_unhide_std_parts_bodies1(self): selection1 = self.productDocument1.Selection selection1.Clear() carm_part = self.select_carm_to_paste_data() std_bodies = carm_part.HybridBodies for body in xrange(1, std_bodies.Count+1): body1 = std_bodies.Item(body) selection1.Add(body1) selection1.visProperties.SetShow(0) selection1.Clear() carm_part.Update() def swich_to_part_design(self): selection1 = self.productDocument1.Selection selection1.Clear() part1 = self.select_carm_to_paste_data() selection1.Add(part1) self.catia.StartWorkbench("PrtCfg") print 'part design' selection1 = self.productDocument1.Selection selection1.Clear() def activate_top_prod(self): selection1 = self.productDocument1.Selection selection1.Clear() product1 = self.productDocument1.Product print product1.Name print product1.PartNumber selection1.Add(product1) target = selection1.Item(1) print target.Name self.catia.StartCommand('FrmActivate') # info on how to use send keys: # wsc = win32com.client.Dispatch("WScript.Shell") # wsc.AppActivate("CATIA V5") # wsc.SendKeys("c:FrmActivate") # wsc.SendKeys("{ENTER}") wb = self.workbench_id() if wb != 'Assembly': self.catia.StartWorkbench("Assembly") self.activate_top_prod() def workbench_id(self): """ Returns workbench name """ wb_name = self.catia.GetWorkbenchId() print str(wb_name) return str(wb_name) def if_stable(self, sta_values_fake): stable_zone = ['0465', '0513', '897', '945', '993', '1041', '1365', '1401', '1401' '1401+0', '1401+48', '1401+96', '1425', '1473', '1521', '1569'] sta = sta_values_fake[self.copy_from_product - 5] if sta in stable_zone: return True else: return False def hide_unhide_captures(self, hide_or_unhide, capture_number): selection1 = self.productDocument1.Selection selection1.Clear() carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) selection1.Add(capture1) if hide_or_unhide == 'hide': selection1.visProperties.SetShow(1) else: selection1.visProperties.SetShow(0) carm_part.Update() print 'edr_unhidden' def hide_unhide_annotations(self, hide_or_unhide, annotation_number): selection1 = self.productDocument1.Selection selection1.Clear() carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) annotations1 = ann_set1.Annotations annotation1 = annotations1.Item(annotation_number) selection1.Add(annotation1) if hide_or_unhide == 'hide': selection1.visProperties.SetShow(1) else: selection1.visProperties.SetShow(0) carm_part.Update() print 'annotatios visibility managed' def map_camera_names(self): """Maps camera names to numbers in order""" cam_dict = {} # carm_part = self.select_carm_to_paste_data() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras for i in xrange(1, cameras.Count+1): camera = cameras.Item(i) cam_dict[str(camera.name)] = i print cam_dict return cam_dict def shift_camera(self, sta_value_pairs, size=None): # carm_part = self.select_carm_to_paste_data() cam_dict = self.map_camera_names() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras coord_to_move = sta_value_pairs[self.copy_from_product - 5] coefficient = coord_to_move - (inch_to_mm(717.0 - float(size) / 2)) print coefficient if self.side == 'LH': all_annotations_origin = [20118.056641+coefficient, 304.427582, 9348.172852] engineering_definition_release_origin = [20120.964844+coefficient, 283.42627, 9091.376953] reference_geometry_origin = [18193.632824+coefficient, 329.830675, 9625.886719] upper_plenum_fasteners_origin = [18212.539063+coefficient, -5217.299805, 8520.522461] upper_plenum_spud_fasteners_origin = [18247.126963+coefficient, 279.302231, 9507.394531] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.4082489, -0.408248, 0.816497] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] reference_geometry_sight_direction = [0, -0.677411, -0.735605] reference_geometry_up_direction = [0, -0.735605, 0.67741] upper_plenum_fasteners_sight_direction = [0, 0.941916, -0.335417] upper_plenum_fasteners_up_direction = [0, 0.335459, 0.942055] upper_plenum_spud_fasteners_sight_direction = [0, -0.67879, -0.734332] upper_plenum_spud_fasteners_up_direction = [0, -0.734331, 0.67879] else: all_annotations_origin = [21650.115234+coefficient, -1780.692627, 9774.560547] engineering_definition_release_origin = [21262.044922+coefficient, -1382.012573, 9473.382813] reference_geometry_origin = [18193.632824+coefficient, -258.215088, 9591.541016] upper_plenum_fasteners_origin = [18504.525391+coefficient, 4084.549561, 8021.676270] upper_plenum_spud_fasteners_origin = [18247.126963+coefficient, -472.800446, 9663.113281] all_annotations_sight_direction = [-0.64431, 0.635349, -0.425672] all_annotations_up_direction = [-0.228644, 0.371113, 0.899998] engineering_definition_sight_direction = [-0.63536, 0.63216, -0.443499] engineering_definition_up_direction = [-0.294015, 0.333029, 0.895905] reference_geometry_sight_direction = [0, 0.677411, -0.735605] reference_geometry_up_direction = [0, 0.735605, 0.677411] upper_plenum_fasteners_sight_direction = [0, -0.946231, -0.323493] upper_plenum_fasteners_up_direction = [0, -0.323493, 0.946231] upper_plenum_spud_fasteners_sight_direction = [0, 0.677411, -0.735605] upper_plenum_spud_fasteners_up_direction = [0, 0.735605, 0.677411] view_origins = [all_annotations_origin, engineering_definition_release_origin, reference_geometry_origin, upper_plenum_fasteners_origin, upper_plenum_spud_fasteners_origin] viewpoints = ['All Annotations', 'Engineering Definition Release', 'Reference Geometry', 'Upper Plenum Fasteners', 'Upper Plenum Spud Fasteners'] sight_directions = [all_annotations_sight_direction, engineering_definition_sight_direction, reference_geometry_sight_direction, upper_plenum_fasteners_sight_direction, upper_plenum_spud_fasteners_sight_direction] up_directions = [all_annotations_up_direction, engineering_definition_up_direction, reference_geometry_up_direction, upper_plenum_fasteners_up_direction, upper_plenum_spud_fasteners_up_direction] dict_cameras = dict(zip(viewpoints, view_origins)) dict_sight_directions = dict(zip(viewpoints, sight_directions)) dict_up_directions = dict(zip(viewpoints, up_directions)) print dict_cameras for view in viewpoints: viewpoint = cameras.Item(cam_dict[view]) print viewpoint.Name # sight_direction = [1,0,0] # PutUpDirection = [1,1,1] # print viewpoint.Viewpoint3D.FocusDistance # print viewpoint.Viewpoint3D.Zoom vpd = viewpoint.Viewpoint3D vpd.PutOrigin(dict_cameras[view]) vpd.PutSightDirection(dict_sight_directions[view]) vpd.PutUpDirection(dict_up_directions[view]) # viewpoint.Viewpoint3D.PutSightDirection(sight_direction) # viewpoint.Viewpoint3D.PutUpDirection(sight_direction) def paste_to_jd(self, jd_number): """Pastes special copied data to JD""" selection2 = self.productDocument1.Selection selection2.Clear() part2 = self.select_carm_to_paste_data() hybridBodies1 = part2.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) selection2.Add(hybridBody2) selection2.PasteSpecial('CATPrtResultWithOutLink') selection2.Clear() part2.Update() def access_captures(self, number): selection3 = self.productDocument1.Selection selection3.Clear() carm_part = self.select_carm_to_paste_data() # KBE = carm_part.GetCustomerFactory("BOEAnntFactory") ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) captures1 = ann_set1.Captures capture1 = captures1.Item(number) print capture1.name capture1.ManageHideShowBody = True capture1.DisplayCapture() # pointers = capture1.Annotations # print pointers.name # for pointer in pointers: # leader = pointers.Item(pointers.Count) # print leader.name # anns = ann_set1.Annotations # jd1_annotation = anns.Item(4) # selection3.Add(jd1_annotation) # selection3.visProperties.SetShow(0) class CarmUpperBin(CarmOmf): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, *args): super(CarmUpperBin, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name) self.side = side self.extention = '\\seed_carm_upr_' + side + '.CATPart' for i in args: if type(i) is list: if len(i) != 0: self.first_elem_in_irm = i[0] self.irm_length = len(i) self.first_elem_in_irm_size = self.first_elem_in_irm[:2] else: self.plug_value = i def select_first_elem_in_irm_product(self): # ICM_1.ApplyWorkMode(2) product1 = self.productDocument1.Product products1 = product1.Products print 'FIRST ELEMENT IN IRM' print self.first_elem_in_irm for prod in xrange(1, 5): product_to_replace = products1.Item(prod) products_to_replace = product_to_replace.Products for det in xrange(1, products_to_replace.Count+1): product_act_to_replace_nonc = products_to_replace.Item(det) if self.first_elem_in_irm in str(product_act_to_replace_nonc.Name): return product_act_to_replace_nonc else: continue for prod in xrange(5, products1.Count+1): product_to_replace = products1.Item(prod) if self.first_elem_in_irm in str(product_to_replace.Name): return product_to_replace else: continue def select_carm_to_paste_data(self): """Returns part of the CARM through the reference product""" Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) Product2 = to_p.ReferenceProduct Product2Products = Product2.Products product_forpaste = Product2Products.Item(3) print product_forpaste.name Part3 = product_forpaste.ReferenceProduct PartDocument3 = Part3.Parent print PartDocument3.name geom_elem3 = PartDocument3.Part return geom_elem3 def change_inst_id_sta(self, sta_values_fake, sta_value_pairs, side, size): finish_sta = sta_value((sta_value_pairs[self.copy_from_product - 5] + inch_to_mm(int(size))), self.plug_value) start_sta = sta_values_fake[self.copy_from_product - (5 + (self.irm_length - 1))] Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) instance_id_IRM = 'ECS_UPR_STA' + start_sta + '-' + finish_sta + '_' + side[0] to_p.Name = instance_id_IRM print to_p.Name def modif_ref_annotation(self, size): carm_part = self.access_carm() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations ref_annotation = anns.Item(1) ann1text = ref_annotation.Text() ann1text_2d = ann1text.Get2dAnnot() ann1text_value = size + 'IN OUTBD BIN SUPPORT REF' ann1text_2d.Text = ann1text_value print ann1text_value ref_annotation.ModifyVisu() def add_ref_annotation(self, sta_value_pairs, size, side, capture_number): """Adds REF annotation""" annot_text = str(size) + 'IN OUTBD BIN SUPPORT REF' carm_part = self.access_carm() self.activate_ref_view() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] + (inch_to_mm(float(size)) * 0.7) if side == 'LH': coefnt = -1 else: coefnt = 1 hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointCoord(coord_to_move_ref_point, coefnt*1878.360480, 7493.000000) geoset2.AppendHybridShape(hybridShapePointCoord1) carm_part.Update() points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) r = points.Item(points.Count) print r.Name userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] y = inch_to_mm(30) z = 0 if side == 'LH': k = -1 else: k = 1 addition = k*(inch_to_mm(float(size) / 2)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 20 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_sta_annotation(self, sta_value_pairs, sta_values_fake, size, side, capture_number): """Adds REF annotation""" sta = sta_values_fake[self.copy_from_product - 5] annot_text = 'STA ' + sta + '\n REF' carm_part = self.access_carm() self.activate_ref_view() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') points = geoset2.HybridShapes hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] + inch_to_mm(0.25) if side == 'LH': coefnt = -1 else: coefnt = 1 hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointCoord(coord_to_move_ref_point, coefnt*1878.360480, 7493.000000) geoset2.AppendHybridShape(hybridShapePointCoord1) carm_part.Update() points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] - inch_to_mm(2) y = inch_to_mm(20) z = 0 if side == 'LH': k = -1 else: k = 1 # addition = k*(Inch_to_mm(float(size)/2))*0 addition = k*(inch_to_mm(2.15)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 1 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) print ann1text_2d.AnchorPosition ann1text_2d.AnchorPosition = 6 print ann1text_2d.AnchorPosition ann1text_2d.FrameType = 3 KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def activate_ref_view(self, jd_number=2): carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) TPSViews = ann_set1.TPSViews view_to_activate = TPSViews.Item(int(jd_number) + 3) # annotationFactory1 = ann_set1.AnnotationFactory ann_set1.ActiveView = view_to_activate # annotationFactory1.ActivateTPSView(ann_set1, view_to_activate) def copy_jd1_fcm10f5cps05wh_and_paste(self, size, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() if type_of_geometry == 'points': product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*LIGHT*-Name = *CENTERLINE*), sel')) selection1.Copy() self.paste_to_jd(1) else: # selection1.Search(str('(Name = ' + size + '*BIN*LIGHT*1_CENTERLINE*), sel')) product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*LIGHT*-Name = *CENTERLINE*), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def copy_jd2_bacs12fa3k3_and_paste(self, size, arch, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() if type_of_geometry == 'points': product1 = self.select_current_product() selection1.Add(product1) if arch: selection1.Search(str('(Name = ' + size + '*ARCH*PLENUM*UPR*-Name = *CENTERLINE*), sel')) else: selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*UPR*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) selection1.Copy() self.paste_to_jd(2) else: product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) if 'ARCH' in self.first_elem_in_irm: selection1.Search(str('(Name = ' + size + '*ARCH*PLENUM*UPR*-Name = *CENTERLINE*), sel')) print 'ARCH' else: selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*UPR*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) print 'NOT ARCH' first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def shift_camera(self, sta_value_pairs, size=None): # carm_part = self.select_carm_to_paste_data() cam_dict = self.map_camera_names() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras coord_to_move = sta_value_pairs[self.copy_from_product - 5] coefficient = coord_to_move - (inch_to_mm(717.0 - float(size) / 2)) print coefficient if self.side == 'LH': all_annotations_origin = [26064.580078+coefficient, 2511.071533, 12036.463867] engineering_definition_release_origin = [25083.328125+coefficient, 2428.004395, 11772.291016] reference_geometry_origin = [19842.460938+coefficient, 2119.930908, 11485.105469] upper_plenum_fasteners_origin = [19780.910156+coefficient, -8050.014648, 9395.449219] upper_plenum_spud_fasteners_origin = [20067.941406+coefficient, 2222.089111, 11494.928711] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.4082489, -0.408248, 0.816497] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] reference_geometry_sight_direction = [0, -0.677411, -0.735605] reference_geometry_up_direction = [0, -0.735605, 0.67741] upper_plenum_fasteners_sight_direction = [0, 0.941916, -0.335417] upper_plenum_fasteners_up_direction = [0, 0.335459, 0.942055] upper_plenum_spud_fasteners_sight_direction = [0, -0.67879, -0.734332] upper_plenum_spud_fasteners_up_direction = [0, -0.734331, 0.67879] else: all_annotations_origin = [26915.755859+coefficient, -3865.631592, 10862.578125] engineering_definition_release_origin = [28407.517578+coefficient, -5007.974121, 11549.362305] reference_geometry_origin = [19574.328125+coefficient, -2151.801514, 11369.263672] upper_plenum_fasteners_origin = [19731.783203+coefficient, 7120.067383, 6091.5625] upper_plenum_spud_fasteners_origin = [19156.607422+coefficient, -1839.441162, 10945.449219] all_annotations_sight_direction = [-0.64431, 0.635349, -0.425672] all_annotations_up_direction = [-0.228644, 0.371113, 0.899998] engineering_definition_sight_direction = [-0.64431, 0.635349, -0.425672] engineering_definition_up_direction = [-0.228644, 0.371113, 0.899998] reference_geometry_sight_direction = [0, 0.677411, -0.735605] reference_geometry_up_direction = [0, 0.735605, 0.677411] upper_plenum_fasteners_sight_direction = [0, -0.981109, 0.193369] upper_plenum_fasteners_up_direction = [0, 0.19337, 0.981126] upper_plenum_spud_fasteners_sight_direction = [0, 0.677411, -0.735605] upper_plenum_spud_fasteners_up_direction = [0, 0.735605, 0.677411] view_origins = [all_annotations_origin, engineering_definition_release_origin, reference_geometry_origin, upper_plenum_fasteners_origin, upper_plenum_spud_fasteners_origin] viewpoints = ['All Annotations', 'Engineering Definition Release', 'Reference Geometry', 'Upper Plenum Fasteners', 'Upper Plenum Spud Fasteners'] sight_directions = [all_annotations_sight_direction, engineering_definition_sight_direction, reference_geometry_sight_direction, upper_plenum_fasteners_sight_direction, upper_plenum_spud_fasteners_sight_direction] up_directions = [all_annotations_up_direction, engineering_definition_up_direction, reference_geometry_up_direction, upper_plenum_fasteners_up_direction, upper_plenum_spud_fasteners_up_direction] dict_cameras = dict(zip(viewpoints, view_origins)) dict_sight_directions = dict(zip(viewpoints, sight_directions)) dict_up_directions = dict(zip(viewpoints, up_directions)) print dict_cameras for view in viewpoints: viewpoint = cameras.Item(cam_dict[view]) print viewpoint.Name # sight_direction = [1,0,0] # PutUpDirection = [1,1,1] # print viewpoint.Viewpoint3D.FocusDistance # print viewpoint.Viewpoint3D.Zoom vpd = viewpoint.Viewpoint3D vpd.PutOrigin(dict_cameras[view]) vpd.PutSightDirection(dict_sight_directions[view]) vpd.PutUpDirection(dict_up_directions[view]) # viewpoint.Viewpoint3D.PutSightDirection(sight_direction) # viewpoint.Viewpoint3D.PutUpDirection(sight_direction) def set_parameters(self, sta_value_pairs, size): carm_part = self.select_carm_to_paste_data() parameters1 = carm_part.Parameters ref_param = parameters1.Item('ref_connector_X') sta_param = parameters1.Item('sta_connector_X') # direct_param = parameters1.Item('view_direction_connector_X') print ref_param.Value print sta_param.Value coord_to_move = sta_value_pairs[self.copy_from_product - 5] print coord_to_move ref_param.Value = coord_to_move + (inch_to_mm(float(size))) - (inch_to_mm(float(size)) * 0.3) sta_param.Value = coord_to_move + inch_to_mm(0.25) # direct_param.Value = coord_to_move + (Inch_to_mm(float(size)/2)) + Inch_to_mm(7.0) print ref_param.Value print sta_param.Value def add_jd_annotation(self, jd_number, sta_value_pairs, size, side, arch, capture_number): """Adds JOINT DEFINITION XX annotation""" annot_text = 'JOINT DEFINITION ' + jd_number carm_part = self.access_carm() self.activate_view(jd_number) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Joint Definition ' + jd_number) points = geoset2.HybridShapes if '1' in str(jd_number): JD_point = self.copy_jd1_fcm10f5cps05wh_and_paste(self.first_elem_in_irm_size, 'find_point') else: JD_point = self.copy_jd2_bacs12fa3k3_and_paste(self.first_elem_in_irm_size, False, 'find_point') JD_point_coord_X = JD_point.X JD_point_X = JD_point_coord_X.Value print JD_point_X wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(1)) userSurface1 = userSurfaces1.Generate(reference1) for point in xrange(2, points.Count): reference2 = carm_part.CreateReferenceFromObject(points.Item(point)) print reference2.name userSurface1.AddReference(reference2) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5 - (self.irm_length - 1)] + JD_point_X print coord_to_move if jd_number == '01': y = inch_to_mm(12) z = 0 if side == 'LH': k = 1 else: k = -1 # addition = k*(Inch_to_mm(float(size)/2)) addition = k * inch_to_mm(12.0) else: y = inch_to_mm(19) z = 0 if side == 'LH': k = -1 else: k = 1 # addition = k*(Inch_to_mm(float(size)/2)) addition = k * inch_to_mm(12.0) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() class CarmUpperBinNonConstant(CarmOmf): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name): super(CarmUpperBinNonConstant, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name) self.side = side self.extention = '\\seed_carm_nonc_' + side + '.CATPart' def select_carm_to_paste_data(self): """Returns part of the CARM through the reference product""" Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) Product2 = to_p.ReferenceProduct Product2Products = Product2.Products product_forpaste = Product2Products.Item(3) print product_forpaste.name Part3 = product_forpaste.ReferenceProduct PartDocument3 = Part3.Parent print PartDocument3.name geom_elem3 = PartDocument3.Part return geom_elem3 def change_inst_id(self): Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) Product2 = to_p.ReferenceProduct Product2Products = Product2.Products product_forpaste = Product2Products.Item(3) product_forpaste.Name = self.instance_id print product_forpaste.Name def add_ref_annotation(self, sta_value_pairs, size, side, capture_number): """Adds REF annotation""" annot_text = str(size) + 'IN OUTBD FRNG SUPPORT REF' carm_part = self.access_carm() self.activate_ref_view() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] + (inch_to_mm(float(size)) / 2.0) # if side == 'LH': # coefnt = -1 # else: # coefnt = 1 # hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(coord_to_move_ref_point, coefnt*1878.360480, 7493.000000) # geoset2.AppendHybridShape(hybridShapePointCoord1) # carm_part.Update() points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference2 = carm_part.CreateReferenceFromObject(points.Item('point_direction')) userSurface2 = userSurfaces1.Generate(reference2) hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(userSurface2, coord_to_move_ref_point, True) geoset2.AppendHybridShape(hybridShapePointCoord1) reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) carm_part.Update() r = points.Item(points.Count) print r.Name userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] y = inch_to_mm(28) z = 0 if side == 'LH': k = -1 else: k = 1 addition = k*(inch_to_mm(float(size) / 2)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 20 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 20) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_sta_annotation(self, sta_value_pairs, sta_values_fake, size, side, capture_number): """Adds REF annotation""" sta = sta_values_fake[self.copy_from_product - 5] annot_text = 'STA ' + sta + '\nREF' carm_part = self.access_carm() self.activate_ref_view() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') points = geoset2.HybridShapes hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] # if side == 'LH': # coefnt = -1 # else: # coefnt = 1 # hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointCoord(coord_to_move_ref_point, coefnt*1878.360480, 7493.000000) # geoset2.AppendHybridShape(hybridShapePointCoord1) # carm_part.Update() points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference2 = carm_part.CreateReferenceFromObject(points.Item('point_direction')) userSurface2 = userSurfaces1.Generate(reference2) hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(userSurface2, coord_to_move_ref_point, True) geoset2.AppendHybridShape(hybridShapePointCoord1) reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) carm_part.Update() userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] y = inch_to_mm(22) z = 0 if side == 'LH': k = -1 else: k = 1 addition = k*(inch_to_mm(2.15)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 1 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 20) ann1text_2d.AnchorPosition = 6 ann1text_2d.FrameType = 3 KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def activate_ref_view(self, jd_number=2): carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) TPSViews = ann_set1.TPSViews view_to_activate = TPSViews.Item(int(jd_number) + 3) # annotationFactory1 = ann_set1.AnnotationFactory ann_set1.ActiveView = view_to_activate # annotationFactory1.ActivateTPSView(ann_set1, view_to_activate) def add_jd_annotation(self, jd_number, sta_value_pairs, size, side, arch, capture_number): """Adds JOINT DEFINITION XX annotation""" annot_text = 'JOINT DEFINITION ' + jd_number carm_part = self.access_carm() KBE = carm_part.GetCustomerFactory("BOEAnntFactory") self.activate_view(jd_number) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Joint Definition ' + jd_number) points = geoset2.HybridShapes #if '1' in str(jd_number): # JD_point = self.copy_jd1_fcm10f5cps05wh_and_paste(size, 'find_point') #else: # JD_point = self.copy_jd2_bacs12fa3k3_and_paste(size, arch, 'find_point') #JD_point_coord_X = JD_point.X #JD_point_X = JD_point_coord_X.Value wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(1)) userSurface1 = userSurfaces1.Generate(reference1) for point in xrange(2, points.Count): reference2 = carm_part.CreateReferenceFromObject(points.Item(point)) print reference2.name userSurface1.AddReference(reference2) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = inch_to_mm(457.917) - (-1 * sta_value_pairs[self.copy_from_product - 5]) # coord_to_move = Inch_to_mm(457.917) - (-1 * sta_value_pairs[self.copy_from_product - 5]) - JD_point_X - Inch_to_mm(float(size)) if jd_number == '01': y = inch_to_mm(12) z = 0 if side == 'LH': k = 1 else: k = -1 # addition = k*(Inch_to_mm(24)) else: y = inch_to_mm(-12) z = 0 if side == 'LH': k = -1 else: k = 1 # addition = k*(Inch_to_mm(24.0)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 16) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() # self.activate_top_prod() def set_parameters(self, sta_value_pairs, size): carm_part = self.select_carm_to_paste_data() parameters1 = carm_part.Parameters ref_param = parameters1.Item('ref_connector_X') sta_param = parameters1.Item('sta_connector_X') # direct_param = parameters1.Item('view_direction_connector_X') print ref_param.Value print sta_param.Value coord_to_move = -1 * (sta_value_pairs[self.copy_from_product - 5]) print coord_to_move sta_param.Value = coord_to_move + (inch_to_mm(float(size))) - inch_to_mm(0.5) ref_param.Value = coord_to_move print ref_param.Value print sta_param.Value def shift_camera(self, sta_value_pairs, size=None): cam_dict = self.map_camera_names() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras coord_to_move = inch_to_mm(457.917) - (-1 * sta_value_pairs[self.copy_from_product - 5]) coefficient = coord_to_move - inch_to_mm(457.917) print coefficient if self.side == 'LH': all_annotations_origin = [13315.510742+coefficient, 696.444824, 9577.463867] engineering_definition_release_origin = [13315.510742+coefficient, 696.444824, 9577.463867] reference_geometry_origin = [10226.757813+coefficient, 1628.633789, 10644.860352] upper_plenum_fasteners_origin = [10692.801758+coefficient, -6077.0, 8673.823242] upper_plenum_spud_fasteners_origin = [11296.463867+coefficient, 1104.921265, 10296.697266] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.4082489, -0.408248, 0.816497] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] reference_geometry_sight_direction = [-0.05904, -0.674833, -0.735605] reference_geometry_up_direction = [-0.064112, -0.735605, 0.67741] upper_plenum_fasteners_sight_direction = [0.080368, 0.949164, -0.30435] upper_plenum_fasteners_up_direction = [0.026448, 0.3032, 0.95256] upper_plenum_spud_fasteners_sight_direction = [-0.05904, -0.674833, -0.735605] upper_plenum_spud_fasteners_up_direction = [-0.064112, -0.735605, 0.67741] else: all_annotations_origin = [8824.277344+coefficient, -1230.204712, 9511.789063] engineering_definition_release_origin = [9241.155273+coefficient, -869.085632, 9268.230469] reference_geometry_origin = [11314.335938+coefficient, -649.952087, 9972.473633] upper_plenum_fasteners_origin = [10815.461914+coefficient, 4949.903809, 8104.419922] upper_plenum_spud_fasteners_origin = [11351.40918+coefficient, -945.137512, 10264.790039] all_annotations_sight_direction = [0.507266, 0.688048, -0.518913] all_annotations_up_direction = [0.304368, 0.420292, 0.854818] engineering_definition_sight_direction = [0.507265, 0.688048, -0.518913] engineering_definition_up_direction = [0.304368, 0.420292, 0.854818] reference_geometry_sight_direction = [-0.05904, 0.674833, -0.735605] reference_geometry_up_direction = [-0.064112, 0.732806, 0.677411] upper_plenum_fasteners_sight_direction = [0.085044, -0.960193, -0.266077] upper_plenum_fasteners_up_direction = [0.021026, -0.265255, 0.963949] upper_plenum_spud_fasteners_sight_direction = [-0.05904, 0.674833, -0.735605] upper_plenum_spud_fasteners_up_direction = [-0.064112, 0.732806, 0.677411] view_origins = [all_annotations_origin, engineering_definition_release_origin, reference_geometry_origin, upper_plenum_fasteners_origin, upper_plenum_spud_fasteners_origin] viewpoints = ['All Annotations', 'Engineering Definition Release', 'Reference Geometry', 'Upper Plenum Fasteners', 'Upper Plenum Spud Fasteners'] sight_directions = [all_annotations_sight_direction, engineering_definition_sight_direction, reference_geometry_sight_direction, upper_plenum_fasteners_sight_direction, upper_plenum_spud_fasteners_sight_direction] up_directions = [all_annotations_up_direction, engineering_definition_up_direction, reference_geometry_up_direction, upper_plenum_fasteners_up_direction, upper_plenum_spud_fasteners_up_direction] dict_cameras = dict(zip(viewpoints, view_origins)) dict_sight_directions = dict(zip(viewpoints, sight_directions)) dict_up_directions = dict(zip(viewpoints, up_directions)) print dict_cameras for view in viewpoints: viewpoint = cameras.Item(cam_dict[view]) print viewpoint.Name # sight_direction = [1,0,0] # PutUpDirection = [1,1,1] # print viewpoint.Viewpoint3D.FocusDistance # print viewpoint.Viewpoint3D.Zoom vpd = viewpoint.Viewpoint3D vpd.PutOrigin(dict_cameras[view]) vpd.PutSightDirection(dict_sight_directions[view]) vpd.PutUpDirection(dict_up_directions[view]) # viewpoint.Viewpoint3D.PutSightDirection(sight_direction) # viewpoint.Viewpoint3D.PutUpDirection(sight_direction) class CarmLowerBin(CarmUpperBin): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, state, *args): super(CarmLowerBin, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, *args) self.side = side self.extention = '\\seed_carm_lwr_' + side + '.CATPart' count = 0 for i in args: if type(i) is list: if len(i) != 0: self.first_elem_in_irm_new = i[0] else: self.plug_value = i #if state == 'final': for i in args: if type(i) is not list: break else: for n in xrange(7): count += 1 if '24' in i[n]: if len(i) == count: print '24 found' self.first_elem_in_irm = i[n] count = 0 break else: continue else: self.first_elem_in_irm = i[n] print 'first_elem_is_' + str(self.first_elem_in_irm) break self.irm_components = i self.irm_length = len(i) self.first_elem_in_irm_size = self.first_elem_in_irm[:2] def copy_jd1_BACS12FA3K20_and_paste(self, size, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() if type_of_geometry == 'points': product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*LWR*BACI12AG3UCM2*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) selection1.Copy() self.paste_to_jd(1) else: product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*LWR*BACI12AG3UCM2*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def copy_jd2_bacs12fa3k3_and_paste_1(self, size, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() if type_of_geometry == 'points': product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*LWR*BACI12AK3CM07*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) selection1.Copy() self.paste_to_jd(2) elif type_of_geometry == 'last_point': product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*LWR*BACI12AK3CM07*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) first_elem = selection1.Item2(selection1.Count2) first_point = first_elem.Value print first_point.Name return first_point else: product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*BIN*PLENUM*LWR*BACI12AK3CM07*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def copy_jd3_BACS12FA3K12_and_paste(self, size, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() if type_of_geometry == 'points': product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*NOZZLE*LOWER*BACI12AH5U375*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) selection1.Copy() self.paste_to_jd(3) else: product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*NOZZLE*LOWER*BACI12AH5U375*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def copy_jd4_bacs12fa3k3_and_paste_2(self, size, type_of_geometry='points'): selection1 = self.productDocument1.Selection selection1.Clear() if type_of_geometry == 'points': product1 = self.select_current_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*OB*BIN*END*FRAME*ECS*NOZZLE*BACI12AK3CM07*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) selection1.Copy() self.paste_to_jd(4) else: product1 = self.select_first_elem_in_irm_product() selection1.Add(product1) selection1.Search(str('(Name = ' + size + '*OB*BIN*END*FRAME*ECS*NOZZLE*BACI12AK3CM07*-(Name = *CENTERLINE*+Name = *ARCH*+Name = *SEC*47*)), sel')) first_elem = selection1.Item2(1) first_point = first_elem.Value print first_point.Name return first_point def set_parameters(self, sta_value_pairs, size): carm_part = self.select_carm_to_paste_data() #carm_part = self.access_carm() parameters1 = carm_part.Parameters FL2_X_param = parameters1.Item('FL2_X') FL3_X_param = parameters1.Item('FL3_X') FL4_X_param = parameters1.Item('FL4_X') FL5_X_param = parameters1.Item('FL5_X') fir_tree_param = parameters1.Item('156-00066a') bacs_param = parameters1.Item('BACS38K2a') FL2_X_param_offset = inch_to_mm(4.0606) FL3_X_param_offset = inch_to_mm(2.1582) FL4_X_param_offset = inch_to_mm(3.0059) FL5_X_param_offset = inch_to_mm(2.4261) fir_tree_param_offset = inch_to_mm(0.4353) bacs_param_offset = inch_to_mm(1.4077) anchor_point = self.copy_jd2_bacs12fa3k3_and_paste_1(size, 'find_point') anchor_point_coord_X = anchor_point.X anchor_point_X = anchor_point_coord_X.Value coord_to_move = sta_value_pairs[self.copy_from_product - 5] print 'SET_PARAMETERS ' + str(coord_to_move) FL2_X_param.Value = coord_to_move + anchor_point_X + FL2_X_param_offset FL3_X_param.Value = coord_to_move + anchor_point_X + FL3_X_param_offset FL4_X_param.Value = coord_to_move + anchor_point_X + FL4_X_param_offset FL5_X_param.Value = coord_to_move + anchor_point_X + FL5_X_param_offset fir_tree_param.Value = coord_to_move + anchor_point_X + fir_tree_param_offset bacs_param.Value = coord_to_move + anchor_point_X + bacs_param_offset def shift_camera(self, sta_value_pairs, size=None): #carm_part = self.select_carm_to_paste_data() cam_dict = self.map_camera_names() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras coord_to_move = sta_value_pairs[self.copy_from_product - 5] coefficient = coord_to_move - (inch_to_mm(717.0 - float(size) / 2)) print coefficient if self.side == 'LH': engineering_definition_release_origin = [12313.794922 + coefficient + 4000.0, -6951.88916, 9594.439453] all_annotations_origin = [10896.336914 + coefficient + 4000.0, -7317.958984, 10955.158203] reference_geometry_origin = [15983.475586 + coefficient + 4000.0, 3519.238281, 7186.692383] lower_plenum_downer_strap_origin = [16046.920898 + coefficient + 4000.0, -7975.490723, 6932.231445] upper_downer_strap_origin = [15985.112305 + coefficient + 4000.0, -7302.797852, 11938.787109] lower_plenum_fastener_jd01_origin = [15939.419922 + coefficient + 4000.0, -9042.191406, 7099.609375] lower_plenum_fastener_jd02_origin = [15958.158203 + coefficient + 4000.0, -6916.774902, 11606.900391] sidewall_nozzle_fastener_jd03_origin = [16082.665039 + coefficient + 4000.0, 4481.557617, 4473.383301] sidewall_nozzle_fastener_jd04_origin = [15905.139648 + coefficient + 4000.0, -8642.466797, 6985.853516] engineering_definition_sight_direction = [0.567468, 0.725849, -0.388744] engineering_definition_up_direction = [0.24319, 0.303315, 0.921335] all_annotations_sight_direction = [0.589343, 0.653958, -0.474356] all_annotations_up_direction = [0.312794, 0.356658, 0.880315] reference_geometry_sight_direction = [0, -1, 0] reference_geometry_up_direction = [0, 0, 1] lower_plenum_downer_strap_sight_direction = [0, 1, 0] lower_plenum_downer_strap_up_direction = [0, 0, 1] upper_downer_strap_sight_direction = [0, 0.734878, -0.6782] upper_downer_strap_up_direction = [0, 0.6782, 0.734878] lower_plenum_fastener_jd01_sight_direction = [0, 1, 0] lower_plenum_fastener_jd01_up_direction = [0, 0, 1] lower_plenum_fastener_jd02_sight_direction = [0, 0.726964, -0.686676] lower_plenum_fastener_jd02_up_direction = [0, 0.686676, 0.726964] sidewall_nozzle_fastener_jd03_sight_direction = [-0.011397, -0.937411, 0.348038] sidewall_nozzle_fastener_jd03_up_direction = [0, 0.348079, 0.937464] sidewall_nozzle_fastener_jd04_sight_direction = [0, 1, 0] sidewall_nozzle_fastener_jd04_up_direction = [0, 0, 1] else: engineering_definition_release_origin = [22140.060547 + coefficient + 4000.0, 8147.486816, 13061.50293] all_annotations_origin = [22481.875 + coefficient + 4000.0, 8442.293945, 13728.501953] reference_geometry_origin = [15888.384766 + coefficient + 4000.0, -10043.158203, 7162.20752] lower_plenum_downer_strap_origin = [16132.829102 + coefficient + 4000.0, 4108.947266, 7107.040039] upper_downer_strap_origin = [16127.881836 + coefficient + 4000.0, 6792.799805, 9425.416016] lower_plenum_fastener_jd01_origin = [15984.461914 + coefficient + 4000.0, 9607.047852, 6911.10498] lower_plenum_fastener_jd02_origin = [16045.074219 + coefficient + 4000.0, 7321.30957, 11803.600586] sidewall_nozzle_fastener_jd03_origin = [16035.198242 + coefficient + 4000.0, -4300.676758, 4722.25293] sidewall_nozzle_fastener_jd04_origin = [16086.536133 + coefficient + 4000.0, 4363.338867, 7020.689941] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.411367, -0.405122, 0.816489] reference_geometry_sight_direction = [0, 1, 0] reference_geometry_up_direction = [0, 0, 1] lower_plenum_downer_strap_sight_direction = [0, -1, 0] lower_plenum_downer_strap_up_direction = [0, 0, 1] upper_downer_strap_sight_direction = [0, -0.888642, -0.458601] upper_downer_strap_up_direction = [0, -0.458601, 0.888642] lower_plenum_fastener_jd01_sight_direction = [0, -1, 0] lower_plenum_fastener_jd01_up_direction = [0, 0, 1] lower_plenum_fastener_jd02_sight_direction = [0, -0.726964, -0.686676] lower_plenum_fastener_jd02_up_direction = [0, -0.686676, 0.726964] sidewall_nozzle_fastener_jd03_sight_direction = [0, 0.945367, 0.325971] sidewall_nozzle_fastener_jd03_up_direction = [0, -0.325973, 0.945379] sidewall_nozzle_fastener_jd04_sight_direction = [0, -1, 0] sidewall_nozzle_fastener_jd04_up_direction = [0, 0, 1] view_origins = [all_annotations_origin, engineering_definition_release_origin, reference_geometry_origin, lower_plenum_downer_strap_origin, upper_downer_strap_origin, lower_plenum_fastener_jd01_origin, lower_plenum_fastener_jd02_origin, sidewall_nozzle_fastener_jd03_origin, sidewall_nozzle_fastener_jd04_origin] viewpoints = ['ALL ANNOTATION', 'ENGINEERING DEFINITION RELEASE', 'REFERENCE GEOMETRY', 'LOWER PLENUM DOWNER STRAP', 'UPPER DOWNER STRAP', 'LOWER PLENUM FASTENER JD01', 'LOWER PLENUM FASTENER JD02', 'SIDEWALL NOZZLE FASTENER JD03', 'SIDEWALL NOZZLE FASTENER JD04'] sight_directions = [all_annotations_sight_direction, engineering_definition_sight_direction, reference_geometry_sight_direction, lower_plenum_downer_strap_sight_direction, upper_downer_strap_sight_direction, lower_plenum_fastener_jd01_sight_direction, lower_plenum_fastener_jd02_sight_direction, sidewall_nozzle_fastener_jd03_sight_direction, sidewall_nozzle_fastener_jd04_sight_direction] up_directions = [all_annotations_up_direction, engineering_definition_up_direction, reference_geometry_up_direction, lower_plenum_downer_strap_up_direction, upper_downer_strap_up_direction, lower_plenum_fastener_jd01_up_direction, lower_plenum_fastener_jd02_up_direction, sidewall_nozzle_fastener_jd03_up_direction, sidewall_nozzle_fastener_jd04_up_direction] dict_cameras = dict(zip(viewpoints, view_origins)) dict_sight_directions = dict(zip(viewpoints, sight_directions)) dict_up_directions = dict(zip(viewpoints, up_directions)) print dict_cameras for view in viewpoints: viewpoint = cameras.Item(cam_dict[view]) print viewpoint.Name #sight_direction = [1,0,0] #PutUpDirection = [1,1,1] #print viewpoint.Viewpoint3D.FocusDistance #print viewpoint.Viewpoint3D.Zoom vpd = viewpoint.Viewpoint3D vpd.PutOrigin(dict_cameras[view]) vpd.PutSightDirection(dict_sight_directions[view]) vpd.PutUpDirection(dict_up_directions[view]) #viewpoint.Viewpoint3D.PutSightDirection(sight_direction) #viewpoint.Viewpoint3D.PutUpDirection(sight_direction) def activate_view(self, view_number): carm_part = self.select_carm_to_paste_data() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) TPSViews = ann_set1.TPSViews view_to_activate = TPSViews.Item(view_number) ann_set1.ActiveView = view_to_activate def select_carm_to_paste_data(self): """Returns part of the CARM through the reference product""" Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) print to_p.Name if '24' in self.first_elem_in_irm_new: order_of_carm_in_tree = 3 else: order_of_carm_in_tree = 4 Product2 = to_p.ReferenceProduct Product2Products = Product2.Products product_forpaste = Product2Products.Item(order_of_carm_in_tree) print product_forpaste.name Part3 = product_forpaste.ReferenceProduct PartDocument3 = Part3.Parent print PartDocument3.name geom_elem3 = PartDocument3.Part return geom_elem3 def set_standard_parts_params(self, jd_number): self.update_hole_qty(jd_number) carm_part = self.select_carm_to_paste_data() parameters1 = carm_part.Parameters selection1 = self.productDocument1.Selection selection1.Clear() hole_qty = self.calculate_jd_points(jd_number) if jd_number == 1: param1 = parameters1.Item('BACS12FA3K20') param1.Value = str(hole_qty) + '|BACS12FA3K20 | SCREW, WASHER HEAD, CROSS RECESS, FULL THREADED, 6AL-4V TITANIUM' param2 = parameters1.Item('BACS38K2') param2.Value = str(hole_qty/2) + '|BACS38K2 | STRAP, ADJUSTABLE' param3 = parameters1.Item('156-00066') param3.Value = str(hole_qty) + '|156-00066 | ASSEMBLY TREE MOUNT AND CABLE TIES' elif jd_number == 2: hole_qty1 = self.calculate_jd_points(4) hole_qty += hole_qty1 param = parameters1.Item('BACS12FA3K3') param.Value = str(hole_qty) + '|BACS12FA3K3 | SCREW, WASHER HEAD, CROSS RECESS, FULL THREADED, 6AL-4V TITANIUM' elif jd_number == 3: param = parameters1.Item('BACS12FA3K12') param.Value = str(hole_qty) + '|BACS12FA3K12 | SCREW, WASHER HEAD, CROSS RECESS, FULL THREADED, 6AL-4V TITANIUM' elif jd_number == 4: pass def calculate_jd_points(self, jd_number): carm_part = self.select_carm_to_paste_data() hole_qty = 0 selection1 = self.productDocument1.Selection selection1.Clear() hybridBodies1 = carm_part.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) HybridShapes1 = hybridBody2.HybridShapes for shape in xrange(HybridShapes1.Count): hole_qty += 1 print hole_qty return hole_qty def update_hole_qty(self, jd_number): carm_part = self.select_carm_to_paste_data() parameters1 = carm_part.Parameters hole_qty = self.calculate_jd_points(jd_number) param_hole_qty = parameters1.Item('Joint Definitions\Joint Definition 0' + str(jd_number) + '\Hole Quantity') param_hole_qty.Value = str(hole_qty) def change_inst_id(self): Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) Product2 = to_p.ReferenceProduct Product2Products = Product2.Products carm_name = to_p.Name carm_name1 = carm_name.replace('_INSTL', '') carm_name2 = carm_name1 + '_CARM' if '24' in self.first_elem_in_irm_new: product_forpaste = Product2Products.Item(3) else: product_forpaste = Product2Products.Item(4) product_forpaste.Name = carm_name2 print product_forpaste.Name def change_inst_id_sta(self, sta_values_fake, sta_value_pairs, side, size): finish_sta = sta_value((sta_value_pairs[self.copy_from_product - 5] + inch_to_mm(int(size))), self.plug_value) start_sta = sta_values_fake[self.copy_from_product - (5 + (self.irm_length - 1))] Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) # Product2Products = Product2.Products # product_forpaste = Product2Products.Item(3) instance_id_IRM = 'ECS_LWR_STA' + start_sta + '-' + finish_sta + '_' + side[0] to_p.Name = instance_id_IRM print to_p.Name def copy_bodies_and_paste(self, fastener): """Makes copy of fasteners solids and pastes them to the current CARM""" selection1 = self.productDocument1.Selection selection1.Clear() product1 = self.select_current_product() selection1.Add(product1) # selection1.Search(str('(Name = ' + fastener + '*REF-Name = *.*), sel')) selection1.Search(str('Name = ' + fastener + '*REF, sel')) try: selection1.Copy() except: pass else: selection2 = self.productDocument1.Selection selection2.Clear() part2 = self.select_carm_to_paste_data() selection2.Add(part2) selection2.PasteSpecial('CATPrtResultWithOutLink') part2.Update() def add_ref_annotation(self, sta_value_pairs, size, side, capture_number): """Adds REF annotation""" annot_text = str(size) + 'IN OUTBD BIN SUPPORT REF' carm_part = self.access_carm() self.activate_view(3) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] + (inch_to_mm(float(size)) * 0.7) if side == 'LH': coefnt = -1 else: coefnt = 1 hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointCoord(coord_to_move_ref_point, coefnt*1878.360480, 7493.000000) geoset2.AppendHybridShape(hybridShapePointCoord1) carm_part.Update() points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) r = points.Item(points.Count) print r.Name userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] y = inch_to_mm(60) z = 0 if side == 'LH': k = -1 else: k = 1 addition = k*(inch_to_mm(float(size) / 2)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 20 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_sta_annotation(self, sta_value_pairs, sta_values_fake, size, side, capture_number): """Adds REF annotation""" sta = sta_values_fake[self.copy_from_product - 5] annot_text = 'STA ' + sta + '\n REF' carm_part = self.access_carm() self.activate_view(3) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') points = geoset2.HybridShapes hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] + inch_to_mm(0.25) if side == 'LH': coefnt = -1 else: coefnt = 1 hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointCoord(coord_to_move_ref_point, coefnt*1878.360480, 7493.000000) geoset2.AppendHybridShape(hybridShapePointCoord1) carm_part.Update() points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5] - inch_to_mm(2) y = inch_to_mm(40) z = 0 if side == 'LH': k = -1 else: k = 1 # addition = k*(Inch_to_mm(float(size)/2))*0 addition = k*(inch_to_mm(2.15)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 1 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) print ann1text_2d.AnchorPosition ann1text_2d.AnchorPosition = 6 print ann1text_2d.AnchorPosition ann1text_2d.FrameType = 3 KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_jd_annotation(self, jd_number, sta_value_pairs, size, side, arch, capture_number): """Adds JOINT DEFINITION XX annotation""" annot_text = 'JOINT DEFINITION ' + jd_number carm_part = self.access_carm() KBE = carm_part.GetCustomerFactory("BOEAnntFactory") # self.activate_view(jd_number) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Joint Definition ' + jd_number) points = geoset2.HybridShapes if '1' in str(jd_number): JD_point = self.copy_jd1_BACS12FA3K20_and_paste(self.first_elem_in_irm_size, 'find_point') elif '2' in str(jd_number): JD_point = self.copy_jd2_bacs12fa3k3_and_paste_1(self.first_elem_in_irm_size, 'find_point') elif '3' in str(jd_number): JD_point = self.copy_jd3_BACS12FA3K12_and_paste(self.first_elem_in_irm_size, 'find_point') else: JD_point = self.copy_jd4_bacs12fa3k3_and_paste_2(self.first_elem_in_irm_size, 'find_point') JD_point_coord_X = JD_point.X JD_point_X = JD_point_coord_X.Value print JD_point_X wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() selection1 = self.productDocument1.Selection selection1.Clear() reference1 = carm_part.CreateReferenceFromObject(points.Item(1)) userSurface1 = userSurfaces1.Generate(reference1) for point in xrange(2, points.Count+1): reference2 = carm_part.CreateReferenceFromObject(points.Item(point)) print reference2.name userSurface1.AddReference(reference2) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = sta_value_pairs[self.copy_from_product - 5 - (self.irm_length - 1)] + JD_point_X print coord_to_move y = inch_to_mm(12) z = 0 if side == 'LH': k = 1 else: k = -1 if '3' in str(jd_number): k = k * (-1) addition = k * inch_to_mm(12.0) captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) view_to_activate = capture1.ActiveView KBE.ActivateTPSView(ann_set1, view_to_activate) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) KBE.AssociateAnntCapture(annotation1, capture1) self.rename_part_body() self.hide_last_annotation() carm_part.Update() def create_jd_vectors(self, jd_number): points_in_geoset = self.points_ammount(jd_number) part1 = self.select_carm_to_paste_data() hybridBodies1 = part1.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) hybridShapes1 = hybridBody2.HybridShapes hybridShapePointCenter1 = hybridShapes1.Item(1) reference1 = part1.CreateReferenceFromObject(hybridShapePointCenter1) hybridShapeFactory1 = part1.HybridShapeFactory hybridBody3 = hybridBodies1.Item("Construction Geometry (REF)") hybridBodies3 = hybridBody3.HybridBodies hybridBody4 = hybridBodies3.Item("Misc Construction Geometry") hybridShapes2 = hybridBody4.HybridShapes hybridShapePlaneOffset1 = hybridShapes2.Item('jd' + str(jd_number) + '_vector_direction') reference2 = part1.CreateReferenceFromObject(hybridShapePlaneOffset1) hybridShapeDirection1 = hybridShapeFactory1.AddNewDirection(reference2) Orientation = True if jd_number == 1: Orientation = False elif jd_number == 4 and self.side == 'RH': Orientation = False if jd_number == 4: for point in range(1, points_in_geoset + 1): hybridShapePointCenter1 = hybridShapes1.Item(point) reference1 = part1.CreateReferenceFromObject(hybridShapePointCenter1) hybridShapeLinePtDir1 = hybridShapeFactory1.AddNewLinePtDir(reference1, hybridShapeDirection1, 0.000000, 25.400000, Orientation) Orientation = not Orientation hybridBody2.AppendHybridShape(hybridShapeLinePtDir1) hybridShapeLinePtDir1.Name = 'FIDV_0' + str(jd_number) #part1.Update() else: hybridShapeLinePtDir1 = hybridShapeFactory1.AddNewLinePtDir(reference1, hybridShapeDirection1, 0.000000, 25.400000, Orientation) hybridBody2.AppendHybridShape(hybridShapeLinePtDir1) hybridShapeLinePtDir1.Name = 'FIDV_0' + str(jd_number) #part1.Update() def points_ammount(self, jd_number): elements_in_geoset = 0 part1 = self.select_carm_to_paste_data() hybridBodies1 = part1.HybridBodies hybridBody1 = hybridBodies1.Item("Joint Definitions") hybridBodies2 = hybridBody1.HybridBodies hybridBody2 = hybridBodies2.Item("Joint Definition" + ' 0' + str(jd_number)) hybridShapes1 = hybridBody2.HybridShapes for i in range(1, hybridShapes1.Count + 1): elements_in_geoset += 1 return elements_in_geoset def modif_lwr_strap_annotation(self): carm_part = self.access_carm() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations sta_annotation = anns.Item(7) ann1text = sta_annotation.Text() ann1text_2d = ann1text.Get2dAnnot() number_of_straps = 0 print self.irm_components for component in self.irm_components: if '24' in str(component): number_of_straps += 1 else: number_of_straps += 2 #ann1text_value = 'STA ' + sta + '\nLBL 74.3\nWL 294.8\nREF' ann1text_value = 'BACS38K2 TYPICAL' + '\n' + str(number_of_straps) + ' PLACES' ann1text_2d.Text = ann1text_value print ann1text_value sta_annotation.ModifyVisu() def modif_upr_strap_annotation(self): carm_part = self.access_carm() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) anns = ann_set1.Annotations sta_annotation = anns.Item(1) ann1text = sta_annotation.Text() ann1text_2d = ann1text.Get2dAnnot() number_of_straps = 0 for component in self.irm_components: if '24' in str(component): number_of_straps += 1 else: number_of_straps += 2 ann1text_value = '156-00066 TYPICAL' + '\n' + str(number_of_straps * 2) + ' PLACES' ann1text_2d.Text = ann1text_value print ann1text_value sta_annotation.ModifyVisu() class CarmOmfNonConstant(CarmUpperBin): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, *args): super(CarmUpperBin, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name) self.side = side self.extention = '\\seed_carm_nonc_irm_' + side + '.CATPart' for i in args: if len(i) != 0: self.first_elem_in_irm = i[0] self.irm_length = len(i) self.first_elem_in_irm_size = self.first_elem_in_irm[:2] def add_jd_annotation(self, jd_number, sta_value_pairs, size, side, arch, capture_number): """Adds JOINT DEFINITION XX annotation""" annot_text = 'JOINT DEFINITION ' + jd_number carm_part = self.access_carm() KBE = carm_part.GetCustomerFactory("BOEAnntFactory") self.activate_view(jd_number) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Joint Definition ' + jd_number) points = geoset2.HybridShapes if '1' in str(jd_number): JD_point = self.copy_jd1_fcm10f5cps05wh_and_paste(self.first_elem_in_irm_size, 'find_point') else: JD_point = self.copy_jd2_bacs12fa3k3_and_paste(self.first_elem_in_irm_size, False, 'find_point') JD_point_coord_X = JD_point.X JD_point_X = JD_point_coord_X.Value print JD_point_X wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference1 = carm_part.CreateReferenceFromObject(points.Item(1)) userSurface1 = userSurfaces1.Generate(reference1) for point in xrange(2, points.Count): reference2 = carm_part.CreateReferenceFromObject(points.Item(point)) print reference2.name userSurface1.AddReference(reference2) annotationFactory1 = ann_set1.AnnotationFactory if jd_number == '01': y = inch_to_mm(12) z = 0 if side == 'LH': k = 1 else: k = -1 #addition = k*(Inch_to_mm(float(size)/2)) addition = k * inch_to_mm(12.0) else: y = inch_to_mm(-10) z = 0 if side == 'LH': k = -1 else: k = 1 #addition = k*(Inch_to_mm(float(size)/2)) addition = k * inch_to_mm(12.0) coord_to_move = inch_to_mm(457.917) + sta_value_pairs[self.copy_from_product - 5] - (inch_to_mm(float(size))) + k * JD_point_X annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() #self.activate_top_prod() def add_ref_annotation(self, sta_value_pairs, size, side, capture_number): """Adds REF annotation""" annot_text = str(size) + 'IN OUTBD BIN SUPPORT REF' carm_part = self.access_carm() self.activate_ref_view() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = -1*(sta_value_pairs[self.copy_from_product - 5]) + (inch_to_mm(float(size)) * 0.3) print 'ref_point: ' + str(coord_to_move_ref_point) points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference2 = carm_part.CreateReferenceFromObject(points.Item('point_direction')) print reference2.Name #userSurface2 = userSurfaces1.Generate(reference2) hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(reference2, coord_to_move_ref_point, False) geoset2.AppendHybridShape(hybridShapePointCoord1) reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) carm_part.Update() r = points.Item(points.Count) print r.Name userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = inch_to_mm(457.917) - coord_to_move_ref_point y = inch_to_mm(-3.0) z = 0 if side == 'LH': k = -1 else: k = 1 addition = -1*k*(inch_to_mm(float(size) / 2)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 20 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 20) KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = edr_view self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_sta_annotation(self, sta_value_pairs, sta_values_fake, size, side, capture_number): """Adds STA annotation""" sta = sta_values_fake[self.copy_from_product - 5] annot_text = 'STA ' + sta + '\n REF' carm_part = self.access_carm() self.activate_ref_view() ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') points = geoset2.HybridShapes hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = -1*(sta_value_pairs[self.copy_from_product - 5]) + (inch_to_mm(float(size))) - inch_to_mm(0.5) points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference2 = carm_part.CreateReferenceFromObject(points.Item('point_direction')) #userSurface2 = userSurfaces1.Generate(reference2) hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(reference2, coord_to_move_ref_point, False) geoset2.AppendHybridShape(hybridShapePointCoord1) reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) carm_part.Update() userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory coord_to_move = inch_to_mm(457.917) - coord_to_move_ref_point y = inch_to_mm(-10.0) z = 0 if side == 'LH': k = -1 else: k = 1 addition = k*(inch_to_mm(2.15)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 1 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 20) ann1text_2d.AnchorPosition = 6 ann1text_2d.FrameType = 3 KBE = carm_part.GetCustomerFactory("BOEAnntFactory") captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) self.rename_part_body() self.hide_last_annotation() carm_part.Update() def set_parameters(self, sta_value_pairs, size): carm_part = self.select_carm_to_paste_data() parameters1 = carm_part.Parameters ref_param = parameters1.Item('ref_connector_X') sta_param = parameters1.Item('sta_connector_X') #direct_param = parameters1.Item('view_direction_connector_X') print ref_param.Value print sta_param.Value coord_to_move = -1 * (sta_value_pairs[self.copy_from_product - 5]) print coord_to_move sta_param.Value = coord_to_move + (inch_to_mm(float(size))) - inch_to_mm(0.5) ref_param.Value = coord_to_move #direct_param.Value = coord_to_move + (Inch_to_mm(float(size)/2)) + Inch_to_mm(7.0) print ref_param.Value print sta_param.Value def change_inst_id_sta(self, sta_values_fake, side): start_sta = sta_values_fake[self.copy_from_product - 5] #actual sta: #finish_sta = int((sta_values_fake[self.copy_from_product - (5 + (self.irm_length - 1))])[1:]) + int(self.first_elem_in_irm_size) finish_sta = 465 Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) #Product2 = to_p.ReferenceProduct #Product2Products = Product2.Products #product_forpaste = Product2Products.Item(3) instance_id_IRM = 'ECS_UPR_STA' + start_sta + '-0' + str(finish_sta) + '_' + side[0] to_p.Name = instance_id_IRM print to_p.Name def shift_camera(self, sta_value_pairs, size=None): #carm_part = self.select_carm_to_paste_data() cam_dict = self.map_camera_names() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras coord_to_move = inch_to_mm(457.917) - (-1 * sta_value_pairs[self.copy_from_product - 5]) coefficient = coord_to_move - inch_to_mm(457.917) print coefficient if self.side == 'LH': all_annotations_origin = [13854.880859+coefficient, 4417.077637, 12727.319336] engineering_definition_release_origin = [13854.880859+coefficient, 4417.077637, 12727.319336] reference_geometry_origin = [9994.436523+coefficient, 1648.96167, 10644.861328] upper_plenum_fasteners_origin = [9306.952148+coefficient, -7007.398926, 8625.181641] upper_plenum_spud_fasteners_origin = [10030.945313+coefficient, 3074.359619, 11994.473633] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.4082489, -0.408248, 0.816497] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] reference_geometry_sight_direction = [-0.05904, -0.674833, -0.735605] reference_geometry_up_direction = [-0.064112, -0.732806, 0.677411] upper_plenum_fasteners_sight_direction = [0.080368, 0.949164, -0.30435] upper_plenum_fasteners_up_direction = [0.026448, 0.3032, 0.95256] upper_plenum_spud_fasteners_sight_direction = [-0.05904, -0.674833, -0.735605] upper_plenum_spud_fasteners_up_direction = [-0.064112, -0.732806, 0.677411] else: all_annotations_origin = [5029.863281+coefficient, -2199.449463, 11174.419922] engineering_definition_release_origin = [5029.863281+coefficient, -2199.449463, 11174.419922] reference_geometry_origin = [10082.896484+coefficient, -2005.115234, 11119.094727] upper_plenum_fasteners_origin = [9481.047852+coefficient, 6939.066406, 8479.819336] upper_plenum_spud_fasteners_origin = [9816.714844+coefficient, -1797.713013, 10870.084961] all_annotations_sight_direction = [0.585162, 0.594175, -0.551853] all_annotations_up_direction = [0.352398, 0.426587, 0.83297] engineering_definition_sight_direction = [0.585162, 0.594175, -0.551853] engineering_definition_up_direction = [0.352398, 0.426587, 0.83297] reference_geometry_sight_direction = [-0.05904, 0.674833, -0.735605] reference_geometry_up_direction = [-0.065312, 0.7327, 0.67741] upper_plenum_fasteners_sight_direction = [0.067624, -0.955728, -0.286376] upper_plenum_fasteners_up_direction = [0.024692, -0.285342, 0.958108] upper_plenum_spud_fasteners_sight_direction = [-0.05904, 0.674833, -0.735605] upper_plenum_spud_fasteners_up_direction = [-0.064112, 0.732806, 0.677411] view_origins = [all_annotations_origin, engineering_definition_release_origin, reference_geometry_origin, upper_plenum_fasteners_origin, upper_plenum_spud_fasteners_origin] viewpoints = ['All Annotations', 'Engineering Definition Release', 'Reference Geometry', 'Upper Plenum Fasteners', 'Upper Plenum Spud Fasteners'] sight_directions = [all_annotations_sight_direction, engineering_definition_sight_direction, reference_geometry_sight_direction, upper_plenum_fasteners_sight_direction, upper_plenum_spud_fasteners_sight_direction] up_directions = [all_annotations_up_direction, engineering_definition_up_direction, reference_geometry_up_direction, upper_plenum_fasteners_up_direction, upper_plenum_spud_fasteners_up_direction] dict_cameras = dict(zip(viewpoints, view_origins)) dict_sight_directions = dict(zip(viewpoints, sight_directions)) dict_up_directions = dict(zip(viewpoints, up_directions)) print dict_cameras for view in viewpoints: viewpoint = cameras.Item(cam_dict[view]) print viewpoint.Name #sight_direction = [1,0,0] #PutUpDirection = [1,1,1] #print viewpoint.Viewpoint3D.FocusDistance #print viewpoint.Viewpoint3D.Zoom vpd = viewpoint.Viewpoint3D vpd.PutOrigin(dict_cameras[view]) vpd.PutSightDirection(dict_sight_directions[view]) vpd.PutUpDirection(dict_up_directions[view]) #viewpoint.Viewpoint3D.PutSightDirection(sight_direction) #viewpoint.Viewpoint3D.PutUpDirection(sight_direction) class CarmLowerBinNonConstant(CarmLowerBin): #def __init__(self, side, *args, **kwargs): #super(CARM_UPR, self).__init__(*args, **kwargs) def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, state, *args): super(CarmLowerBin, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, *args) self.side = side self.extention = '\\seed_carm_nonc_lwr_' + side + '.CATPart' for i in args: if len(i) != 0: self.first_elem_in_irm_new = i[0] if state == 'final': for i in args: for n in xrange(len(i)): # for n in i: if '24' in i[n]: continue else: self.first_elem_in_irm = i[n] break self.irm_components = i self.irm_length = len(i) self.first_elem_in_irm_size = self.first_elem_in_irm[:2] def set_parameters(self, sta_value_pairs, size): carm_part = self.select_carm_to_paste_data() #carm_part = self.access_carm() parameters1 = carm_part.Parameters FL2_X_param = parameters1.Item('FL2_X') FL3_X_param = parameters1.Item('FL3_X') FL4_X_param = parameters1.Item('FL4_X') FL5_X_param = parameters1.Item('FL5_X') fir_tree_param = parameters1.Item('156-00066a') bacs_param = parameters1.Item('BACS38K2a') FL2_X_param_offset = inch_to_mm(4.0606) FL3_X_param_offset = inch_to_mm(2.1582) FL4_X_param_offset = inch_to_mm(3.0059) FL5_X_param_offset = inch_to_mm(2.4261) fir_tree_param_offset = inch_to_mm(0.4353) bacs_param_offset = inch_to_mm(1.4077) anchor_point = self.copy_jd2_bacs12fa3k3_and_paste_1(size, 'first_point') k = -1 anchor_point_coord_X = anchor_point.X anchor_point_X = anchor_point_coord_X.Value print 'lwrs_params:' + str(anchor_point_X) #coord_to_move = sta_value_pairs[self.copy_from_product - 5] coord_to_move = -1 * (sta_value_pairs[self.copy_from_product - 5]) print 'lwrs_params:' + str(coord_to_move) print coord_to_move print size FL2_X_param.Value = coord_to_move + (inch_to_mm(float(size)) - inch_to_mm(0.25) - anchor_point_X) + k * FL2_X_param_offset FL3_X_param.Value = coord_to_move + (inch_to_mm(float(size)) - inch_to_mm(0.25) - anchor_point_X) + k * FL3_X_param_offset FL4_X_param.Value = coord_to_move + (inch_to_mm(float(size)) - inch_to_mm(0.25) - anchor_point_X) + k * FL4_X_param_offset FL5_X_param.Value = coord_to_move + (inch_to_mm(float(size)) - inch_to_mm(0.25) - anchor_point_X) + k * FL5_X_param_offset fir_tree_param.Value = coord_to_move + (inch_to_mm(float(size)) - inch_to_mm(0.25) - anchor_point_X) + k * fir_tree_param_offset bacs_param.Value = coord_to_move + (inch_to_mm(float(size)) - inch_to_mm(0.25) - anchor_point_X) + k * bacs_param_offset def change_inst_id_sta(self, sta_values_fake, side): start_sta = sta_values_fake[self.copy_from_product - 5] # actual station: #finish_sta = int((sta_values_fake[self.copy_from_product - (5 + (self.irm_length - 1))])[1:]) + int(self.first_elem_in_irm_size) finish_sta = 465 Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) #Product2 = to_p.ReferenceProduct instance_id_IRM = 'ECS_LWR_STA' + start_sta + '-0' + str(finish_sta) + '_' + side[0] to_p.Name = instance_id_IRM print to_p.Name def shift_camera(self, sta_value_pairs, size=None): #carm_part = self.select_carm_to_paste_data() cam_dict = self.map_camera_names() documents1 = self.catia.Documents partDocument1 = documents1.Item('CA' + self.carm_part_number + '.CATPart') cameras = partDocument1.Cameras #coord_to_move = sta_value_pairs[self.copy_from_product - 5] #coefficient = coord_to_move - (Inch_to_mm(717.0 - float(size)/2)) coord_to_move = inch_to_mm(457.917) - (-1 * sta_value_pairs[self.copy_from_product - 5]) coefficient = coord_to_move - inch_to_mm(457.917) print coefficient if self.side == 'LH': engineering_definition_release_origin = [13944.40332 + coefficient, 2419.441406, 11147.487305] all_annotations_origin = [18506.052734 + coefficient, 6726.539063, 15580.635742] reference_geometry_origin = [10613.700195 + coefficient, 4517.101563, 7088.336914] lower_plenum_downer_strap_origin = [9381.522461 + coefficient, -7979.621094, 7004.487793] upper_downer_strap_origin = [9314.950195 + coefficient, -5907.354004, 10929.607422] lower_plenum_fastener_jd01_origin = [9201.066406 + coefficient, -8280.686523, 7016.032227] lower_plenum_fastener_jd02_origin = [9301.005859 + coefficient, -5827.109375, 10699.782227] sidewall_nozzle_fastener_jd03_origin = [10391.533203 + coefficient, 1334.777466, 7020.099121] sidewall_nozzle_fastener_jd04_origin = [9310.69043 + coefficient, -8233.225586, 7042.39502] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.408248, -0.408248, 0.816497] reference_geometry_sight_direction = [-0.087156, -0.996195, 0] reference_geometry_up_direction = [0, 0, 1] lower_plenum_downer_strap_sight_direction = [0.084765, 0.732081, 0.000192] lower_plenum_downer_strap_up_direction = [0, 0, 1] upper_downer_strap_sight_direction = [0.064049, 0.734878, -0.6782] upper_downer_strap_up_direction = [0.059109, 0.675619, 0.734878] lower_plenum_fastener_jd01_sight_direction = [0.087156, 0.996195, 0] lower_plenum_fastener_jd01_up_direction = [0, 0, 1] lower_plenum_fastener_jd02_sight_direction = [0.063359, 0.724197, -0.686676] lower_plenum_fastener_jd02_up_direction = [0.059848, 0.684063, 0.726964] sidewall_nozzle_fastener_jd03_sight_direction = [-0.087156, -0.996195, 0] sidewall_nozzle_fastener_jd03_up_direction = [0, 0, 1] sidewall_nozzle_fastener_jd04_sight_direction = [0.087156, 0.996195, 0] sidewall_nozzle_fastener_jd04_up_direction = [0, 0, 1] else: engineering_definition_release_origin = [17127.736328 + coefficient, 8979.547852, 14095.664063] all_annotations_origin = [19730.648438 + coefficient, 11429.279297, 16656.181641] reference_geometry_origin = [10325.015625 + coefficient, -4908.834961, 7130.697266] lower_plenum_downer_strap_origin = [9605.200195 + coefficient, 6803.354004, 6960.905762] upper_downer_strap_origin = [9594.720703 + coefficient, 7206.265137, 9366.074219] lower_plenum_fastener_jd01_origin = [9499.174805 + coefficient, 8518.854492, 7055.207031] lower_plenum_fastener_jd02_origin = [9858.34375 + coefficient, 7175.333008, 11960.477539] sidewall_nozzle_fastener_jd03_origin = [10277.820313 + coefficient, -4771.490723, 6982.922363] sidewall_nozzle_fastener_jd04_origin = [9663.085938 + coefficient, 8862.500977, 7014.87207] engineering_definition_sight_direction = [-0.57735, -0.57735, -0.57735] engineering_definition_up_direction = [-0.408248, -0.408248, 0.816497] all_annotations_sight_direction = [-0.57735, -0.57735, -0.57735] all_annotations_up_direction = [-0.411367, -0.405122, 0.816489] reference_geometry_sight_direction = [-0.087156, 0.996195, 0] reference_geometry_up_direction = [0, 0, 1] lower_plenum_downer_strap_sight_direction = [0.087156, -0.996195, 0] lower_plenum_downer_strap_up_direction = [0, 0, 1] upper_downer_strap_sight_direction = [0.080403, -0.919007, -0.385956] upper_downer_strap_up_direction = [0.033638, -0.384487, 0.922517] lower_plenum_fastener_jd01_sight_direction = [0.087156, -0.996195, 0] lower_plenum_fastener_jd01_up_direction = [0, 0, 1] lower_plenum_fastener_jd02_sight_direction = [0.063359, -0.724197, -0.686676] lower_plenum_fastener_jd02_up_direction = [0.059848, -0.684063, 0.726964] sidewall_nozzle_fastener_jd03_sight_direction = [-0.087156, 0.996195, 0] sidewall_nozzle_fastener_jd03_up_direction = [0, 0, 1] sidewall_nozzle_fastener_jd04_sight_direction = [0.087156, -0.996195, 0] sidewall_nozzle_fastener_jd04_up_direction = [0, 0, 1] view_origins = [all_annotations_origin, engineering_definition_release_origin, reference_geometry_origin, lower_plenum_downer_strap_origin, upper_downer_strap_origin, lower_plenum_fastener_jd01_origin, lower_plenum_fastener_jd02_origin, sidewall_nozzle_fastener_jd03_origin, sidewall_nozzle_fastener_jd04_origin] viewpoints = ['ALL ANNOTATION', 'ENGINEERING DEFINITION RELEASE', 'REFERENCE GEOMETRY', 'LOWER PLENUM DOWNER STRAP', 'UPPER DOWNER STRAP', 'LOWER PLENUM FASTENER JD01', 'LOWER PLENUM FASTENER JD02', 'SIDEWALL NOZZLE FASTENER JD03', 'SIDEWALL NOZZLE FASTENER JD04'] sight_directions = [all_annotations_sight_direction, engineering_definition_sight_direction, reference_geometry_sight_direction, lower_plenum_downer_strap_sight_direction, upper_downer_strap_sight_direction, lower_plenum_fastener_jd01_sight_direction, lower_plenum_fastener_jd02_sight_direction, sidewall_nozzle_fastener_jd03_sight_direction, sidewall_nozzle_fastener_jd04_sight_direction] up_directions = [all_annotations_up_direction, engineering_definition_up_direction, reference_geometry_up_direction, lower_plenum_downer_strap_up_direction, upper_downer_strap_up_direction, lower_plenum_fastener_jd01_up_direction, lower_plenum_fastener_jd02_up_direction, sidewall_nozzle_fastener_jd03_up_direction, sidewall_nozzle_fastener_jd04_up_direction] dict_cameras = dict(zip(viewpoints, view_origins)) dict_sight_directions = dict(zip(viewpoints, sight_directions)) dict_up_directions = dict(zip(viewpoints, up_directions)) print dict_cameras for view in viewpoints: viewpoint = cameras.Item(cam_dict[view]) print viewpoint.Name #sight_direction = [1,0,0] #PutUpDirection = [1,1,1] #print viewpoint.Viewpoint3D.FocusDistance #print viewpoint.Viewpoint3D.Zoom vpd = viewpoint.Viewpoint3D vpd.PutOrigin(dict_cameras[view]) vpd.PutSightDirection(dict_sight_directions[view]) vpd.PutUpDirection(dict_up_directions[view]) #viewpoint.Viewpoint3D.PutSightDirection(sight_direction) #viewpoint.Viewpoint3D.PutUpDirection(sight_direction) def add_jd_annotation(self, jd_number, sta_value_pairs, size, side, arch, capture_number): """Adds JOINT DEFINITION XX annotation""" annot_text = 'JOINT DEFINITION ' + jd_number carm_part = self.access_carm() #self.activate_view(jd_number) ann_sets = carm_part.AnnotationSets KBE = carm_part.GetCustomerFactory("BOEAnntFactory") ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Joint Definitions') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Joint Definition ' + jd_number) points = geoset2.HybridShapes if '1' in str(jd_number): JD_point = self.copy_jd1_BACS12FA3K20_and_paste(self.first_elem_in_irm_size, 'find_point') elif '2' in str(jd_number): JD_point = self.copy_jd2_bacs12fa3k3_and_paste_1(self.first_elem_in_irm_size, 'find_point') elif '3' in str(jd_number): JD_point = self.copy_jd3_BACS12FA3K12_and_paste(self.first_elem_in_irm_size, 'find_point') else: JD_point = self.copy_jd4_bacs12fa3k3_and_paste_2(self.first_elem_in_irm_size, 'find_point') JD_point_coord_X = JD_point.X JD_point_X = JD_point_coord_X.Value print JD_point_X wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() selection1 = self.productDocument1.Selection selection1.Clear() reference1 = carm_part.CreateReferenceFromObject(points.Item(1)) userSurface1 = userSurfaces1.Generate(reference1) for point in xrange(2, points.Count+1): reference2 = carm_part.CreateReferenceFromObject(points.Item(point)) print reference2.name userSurface1.AddReference(reference2) annotationFactory1 = ann_set1.AnnotationFactory #coord_to_move = sta_value_pairs[self.copy_from_product - 5 - (self.irm_length - 1)] + JD_point_X y = inch_to_mm(12) z = 0 if side == 'LH': k = 1 else: k = -1 if '3' in str(jd_number): k = k * (-1) addition = k * inch_to_mm(12.0) coord_to_move = inch_to_mm(457.917) + sta_value_pairs[self.copy_from_product - 5] - (inch_to_mm(float(size))) + k * JD_point_X print coord_to_move captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) view_to_activate = capture1.ActiveView KBE.ActivateTPSView(ann_set1, view_to_activate) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) KBE.AssociateAnntCapture(annotation1, capture1) self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_sta_annotation(self, sta_value_pairs, sta_values_fake, size, side, capture_number): """Adds REF annotation""" sta = sta_values_fake[self.copy_from_product - 5] annot_text = 'STA ' + sta + '\n REF' carm_part = self.access_carm() KBE = carm_part.GetCustomerFactory("BOEAnntFactory") self.activate_view(3) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') points = geoset2.HybridShapes hybridShapeFactory1 = carm_part.HybridShapeFactory coord_to_move_ref_point = -1*(sta_value_pairs[self.copy_from_product - 5]) + (inch_to_mm(float(size))) - inch_to_mm(0.5) points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference2 = carm_part.CreateReferenceFromObject(points.Item('point_direction')) hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(reference2, coord_to_move_ref_point, False) geoset2.AppendHybridShape(hybridShapePointCoord1) reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) carm_part.Update() userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory #coord_to_move = sta_value_pairs[self.copy_from_product - 5] - Inch_to_mm(2) coord_to_move = inch_to_mm(457.917) - coord_to_move_ref_point y = inch_to_mm(40) z = 0 if side == 'LH': k = -1 else: k = 1 #addition = k*(Inch_to_mm(float(size)/2))*0 addition = k*(inch_to_mm(2.15)) captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) #view_to_activate = capture1.ActiveView #KBE.ActivateTPSView(ann_set1, view_to_activate) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 1 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) print ann1text_2d.AnchorPosition ann1text_2d.AnchorPosition = 6 print ann1text_2d.AnchorPosition ann1text_2d.FrameType = 3 KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = view_to_activate self.rename_part_body() self.hide_last_annotation() carm_part.Update() def add_ref_annotation(self, sta_value_pairs, size, side, capture_number): """Adds REF annotation""" annot_text = str(size) + 'IN OUTBD BIN SUPPORT REF' carm_part = self.access_carm() KBE = carm_part.GetCustomerFactory("BOEAnntFactory") self.activate_view(3) ann_sets = carm_part.AnnotationSets ann_set1 = ann_sets.Item(1) userSurfaces1 = carm_part.UserSurfaces geosets = carm_part.HybridBodies geoset1 = geosets.Item('Construction Geometry (REF)') geosets1 = geoset1.HybridBodies geoset2 = geosets1.Item('Misc Construction Geometry') hybridShapeFactory1 = carm_part.HybridShapeFactory #coord_to_move_ref_point = sta_value_pairs[self.copy_from_product - 5] + (Inch_to_mm(float(size))*0.7) coord_to_move_ref_point = -1*(sta_value_pairs[self.copy_from_product - 5]) + (inch_to_mm(float(size)) * 0.5) print 'ref_point: ' + str(coord_to_move_ref_point) points = geoset2.HybridShapes wb = str(self.workbench_id()) if wb != 'PrtCfg': self.swich_to_part_design() reference2 = carm_part.CreateReferenceFromObject(points.Item('point_direction')) print reference2.Name hybridShapePointCoord1 = hybridShapeFactory1.AddNewPointOnCurveFromDistance(reference2, coord_to_move_ref_point, False) geoset2.AppendHybridShape(hybridShapePointCoord1) reference1 = carm_part.CreateReferenceFromObject(points.Item(points.Count)) carm_part.Update() r = points.Item(points.Count) print r.Name userSurface1 = userSurfaces1.Generate(reference1) annotationFactory1 = ann_set1.AnnotationFactory #coord_to_move = sta_value_pairs[self.copy_from_product - 5] coord_to_move = inch_to_mm(457.917) - coord_to_move_ref_point y = inch_to_mm(60) z = 0 if side == 'LH': k = -1 else: k = 1 addition = k*(inch_to_mm(float(size) / 2)) annotation1 = annotationFactory1.CreateEvoluateText(userSurface1, k * coord_to_move + addition, y, z, True) ann_text = annotation1.Text() ann1text_2d = ann_text.Get2dAnnot() text_leaders = ann1text_2d.Leaders text_leader1 = text_leaders.Item(1) text_leader1.HeadSymbol = 20 ann1text_2d.Text = annot_text ann1text_2d.SetFontSize(0, 0, 24) captures1 = ann_set1.Captures capture1 = captures1.Item(capture_number) KBE.AssociateAnntCapture(annotation1, capture1) #ann_set1.ActiveView = view_to_activate self.rename_part_body() self.hide_last_annotation() carm_part.Update() class CarmUpperBinNonConstantSection47(CarmUpperBin): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, *args): super(CarmUpperBin, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name) self.side = side self.extention = '\\seed_carm_nonc_irm_' + side + '.CATPart' for i in args: if type(i) is list: if len(i) != 0: self.first_elem_in_irm = i[0] self.irm_length = len(i) self.first_elem_in_irm_size = self.first_elem_in_irm[:2] else: self.plug_value = i def change_inst_id_sta(self, sta_values_fake, sta_value_pairs, side, size): start_sta = sta_values_fake[self.copy_from_product - (5 + (self.irm_length - 1))] finish_sta = int(sta_values_fake[self.copy_from_product - 5]) + int(size) Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) # Product2 = to_p.ReferenceProduct #Product2Products = Product2.Products #product_forpaste = Product2Products.Item(3) instance_id_IRM = 'ECS_UPR_STA' + start_sta + '-' + str(finish_sta) + '_' + side[0] to_p.Name = instance_id_IRM print to_p.Name class CarmLowerBinNonConstantSection47(CarmLowerBin): def __init__(self, carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, state, *args): super(CarmLowerBin, self).__init__(carm_part_number, instance_id, side, order_of_new_product, copy_from_product, cfp_name, *args) self.side = side self.extention = '\\seed_carm_nonc_lwr_' + side + '.CATPart' for i in args: if type(i) is list: if len(i) != 0: self.first_elem_in_irm_new = i[0] else: self.plug_value = i if state == 'final': for i in args: if type(i) is not list: break else: for n in xrange(7): if '24' in i[n]: continue else: self.first_elem_in_irm = i[n] break self.irm_length = len(i) self.first_elem_in_irm_size = self.first_elem_in_irm[:2] def change_inst_id_sta(self, sta_values_fake, sta_value_pairs, side, size): start_sta = sta_values_fake[self.copy_from_product - (5 + (self.irm_length - 1))] finish_sta = int(sta_values_fake[self.copy_from_product - 5]) + int(size) Prod = self.productDocument1.Product collection = Prod.Products to_p = collection.Item(self.order_of_new_product) # Product2 = to_p.ReferenceProduct #Product2Products = Product2.Products #product_forpaste = Product2Products.Item(3) instance_id_IRM = 'ECS_LWR_STA' + start_sta + '-' + str(finish_sta) + '_' + side[0] to_p.Name = instance_id_IRM print to_p.Name #class PartNumbering(object): # # """ # roll - Z, irm_type - X, nozzle_type - Y # """ # # def __init__(self, start_sta, irm_type, nozzle_type, irm_elements, roll): # self.start_sta = start_sta # self.irm_type = irm_type # self.nozzle_type = nozzle_type # self.roll = roll # self.irm_elements = irm_elements # # section1 = 345 # section2 = 465 # section3 = 561 # section4 = 657 # section5 = 897 # section6 = 1089 # section7 = 1293 # section8 = 1401+96 # section9 = 1618 # section10 = 1769 # # irm_type_dict = {'UPR':1, 'LWR':2, 'OMF':3} # # nozzle_type_dict = {'economy':4, 'premium':5} # # zone_dict = {xrange(section1, section2):'IR830Z091', xrange(section2, section3):'IR830Z092', xrange(section3, section4):'IR830Z092', xrange(section4, section5):'IR830Z093', xrange(section5, section6):'IR830Z093', xrange(section6, section7):'IR830Z094', xrange(section7, section8):'IR830Z095', xrange(section8, section9):'IR830Z095', xrange(section9, section10):'IR830Z096'} # # config01 = [(24, 42, 48), (48, 48), (48, 48, 48, 36), (24, 36, 48, 48, 48), (48, 48, 48, 48), (48, 48, 48, 36, 24), (36, 48, 48), (48, 48, 48, 48, 48), (48, 36, 24)] # config03 = [(243, 36, 48), (48, 48), (48, 48, 24, 36, 24), (24, 36, 42, 48, 48), (48, 48, 48, 48), (48, 48, 42, 36, 243), (36, 48, 48), (48, 48, 48, 48, 48), (42, 36, 243)] # config05 = [(24, 36, 48), (48, 48), (48, 48, 42, 36), (48, 48, 48, 48), (48, 48, 48, 48), (48, 48, 48, 48), (36, 48, 48), (48, 48, 48, 48, 48), (48, 48)] # config07 = [(48, 48), (48, 48), (48, 42, 24, 36, 24), (24, 24, 48, 48, 48), (48, 48, 48, 48), (48, 48, 48, 24, 24), (36, 48, 48), (48, 48, 48, 48, 48), (48, 24, 24)] # config09 = [(42, 48), (48, 48), (48, 42, 24, 36, 243), (42, 48, 48, 48), (48, 48, 48, 48), (48, 48, 48, 42), (36, 48, 48), (48, 48, 48, 48, 48), (48, 42)] # config11 = [(36, 48), (48, 48), (48, 48, 48, 24), (36, 48, 48, 48), (48, 48, 48, 48), (48, 48, 48, 36), (36, 48, 48), (48, 48, 48, 48, 48), (48, 36)] # config13 = [(36, 42), (48, 48), (48, 36, 36, 42), (36, 42, 48, 48), (48, 48, 48, 48), (48, 48, 42, 36), (36, 48, 48), (48, 48, 48, 48, 48), (42, 36)] # config15 = [(24, 48), (48, 48), (48, 48, 36, 24), (24, 48, 48, 48), (48, 48, 48, 48), (48, 48, 48, 24), (36, 48, 48), (48, 48, 48, 48, 48), (48, 24)] # config17 = [(24, 42), (48, 48), (48, 36, 36, 36), (24, 42, 48, 48), (48, 48, 48, 48), (48, 48, 42, 24), (36, 48, 48), (48, 48, 48, 48, 48), (42, 24)] # config19 = [(24, 36), (48, 48), (48, 42, 24, 36), (24, 36, 48, 48), (48, 48, 48, 48), (48, 48, 36, 24), (36, 48, 48), (48, 48, 48, 48, 48), (36, 24)] # config21 = [(24, 36), (48, 48), (48, 48, 48), (24, 36, 42, 48), (48, 48, 48, 48), (48, 42, 36, 24), (36, 48, 48), (48, 48, 48, 48, 48), [48]] # config23 = [[48], (48, 48), (48, 48, 42), (48, 48, 48), (48, 48, 48, 48), (48, 48, 48), (36, 48, 48), (48, 48, 48, 48, 48), [42]] # config25 = [[48], (48, 48), (48, 48, 36), (42, 48, 48), (48, 48, 48, 48), (48, 48, 42), (36, 48, 48), (48, 48, 48, 48, 48), []] # config27 = [[42], (48, 48), (48, 42, 36), (42, 48, 48), (48, 48, 48, 48), (48, 48, 42), (36, 48, 48), (48, 48, 48, 48, 48), []] # config29 = [[42], (48, 48), (48, 48, 24), (36, 48, 48), (48, 48, 48, 48), (48, 48, 36), (36, 48, 48), (48, 48, 48, 48, 48), []] # config31 = [[36], (48, 48), (48, 42, 24), (36, 48, 48), (48, 48, 48, 48), (48, 48, 36), (36, 48, 48), (48, 48, 48, 48, 48), []] # config33 = [[36], (48, 48), (48, 42, 24), (36, 42, 48), (48, 48, 48, 48), (48, 42, 36), (36, 48, 48), (48, 48, 48, 48, 48), []] # config35 = [[], (48, 48), (48, 42, 24), (36, 42, 48), (48, 48, 48, 48), (48, 42, 36), (36, 48, 48), (48, 48, 48, 48, 48), []] # config37 = [[], (48, 48), (48, 36, 24), (24, 48, 48), (48, 48, 48, 48), (48, 48, 24), (36, 48, 48), (48, 48, 48, 48, 48), []] # config39 = [[], (48, 48), (48, 36, 24), (24, 48, 48), (48, 48, 48, 48), (48, 48, 24), (36, 48, 48), (48, 48, 48, 48, 48), []] # config41 = [[], (48, 48), (48, 36, 24), (24, 48, 48), (48, 48, 48, 48), (48, 48, 24), (36, 48, 48), (48, 48, 48, 48, 48), []] #x1 = CARM('830Z1000-2194', 'INSTL_UPR_AIR_DIST_OMF_CARM', 'LH', 2, 1) #x2 = CARM('8755675', 2) #prod = ProductECS() #group = [prod] #key = '24RH' #print prod.template_finder(key) #sta_value_pairs = [18211.8, 20650.199999999997, 18211.8, 20650.199999999997] #a = Inch_to_mm(1) #print a #for i in group: #x1.add_carm_as_external_component() #x1.access_captures(2) #x1.hide_unhide_annotations('hide', 1) #x1.hide_unhide_annotations('hide', 2) #x1.manage_annotations_visibility() #x1.add_jd_annotation('01', sta_value_pairs, '54', 'LH') #x1.switch_to_part_design() #x1.activate_top_prod() #x1.activate_top_prod() #x1.change_inst_id() #i.rename_carm() #i.add_geosets() #i.access_annotations() #i.get_points() #i.set_parameters() #i.unused_copy_bodies_and_paste('Part1.CATPart', 'CA03.CATPart') #i.unused_copy_ref_surface_and_paste('Part1.CATPart', 'CA03.CATPart') #i.unused_copy_jd1_fcm10f5cps05wh_and_paste('Thirty.CATPart', 'seed_carm.CATPart') #i.unused_copy_jd2_bacs12fa3k3_and_paste('Thirty.CATPart', 'seed_carm.CATPart') #x1.map_camera_names() #x1.shift_camera() #i.find_parent('Eighteen_solids301.CATProduct') #i.add_jd_annotation(15) #d = i.irms_mapper() #print d #val = i.text_finder('six', d) #print val #dt = i.form_dict() #print dt #print dt.keys() #print dt['Fifty_four']
{ "repo_name": "zy964c/ECS-tool", "path": "carm3.py", "copies": "1", "size": "144566", "license": "unlicense", "hash": -7282257869168356000, "line_mean": 46.6754208754, "line_max": 397, "alpha_frac": 0.6092303861, "autogenerated": false, "ratio": 3.205881048476516, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9301838349118992, "avg_score": 0.0026546170915048824, "num_lines": 2970 }
from functions import isPrime numberPrimes = 100 P = [] def fillP(): count, t = 0,2 while count < numberPrimes: if isPrime(t): P.append(t) count +=1 t+=1 fillP() def nb(n,a): '''nb of different ways to write n as the sum of numbers that are all greater or egal to P[a]''' if P[a] == n or n==0 : return 1 if P[a] >n: return -1 s=0 L = [i for i in range(len(P)) if i>=a] # print 'L',L for b in L: # print b,P[b], n - P[b], nb(n-P[b],b) if nb(n-P[b],b) > 0: s+= nb(n-P[b],b) # print n,b, P[b], nb(n-P[b],b),s return s limit=100 length = len(P) print P, length # can not calculate directly from nb(n,a) because it takes too much of time, due to # the fact that the value isn't stocked during the process def main(): A=[] #A[n][a] = nb(n,a) for n in range(0,limit+1): A.append([]) for a in range(0,length): A[n].append(0) for n in range(0,limit+1): for a in range(0,length): if P[a] == n or n==0 : A[n][a] = 1 elif P[a] >n: A[n][a] = -1 else: s=0 for b in range(a,length): if n >= P[b] and A[n-P[b]][b] > 0: # print n,b, nb(n-P[b],b) s+= A[n-P[b]][b] A[n][a] = s print nb(5,0), A[5][0], A[limit][0] n = 2 while n < limit and A[n][0] <= 5000: n+=1 print 'answer=', n, A[n][0] main()
{ "repo_name": "nguyenkims/projecteuler-python", "path": "src/p77.py", "copies": "1", "size": "1281", "license": "mit", "hash": -4549441328692360700, "line_mean": 20.0163934426, "line_max": 83, "alpha_frac": 0.5448868072, "autogenerated": false, "ratio": 2.1421404682274248, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3187027275427425, "avg_score": null, "num_lines": null }
from functions import * from analysis_functions import * from plot_functions import * import numpy as np import cPickle import matplotlib.pyplot as plt from store_functions import * import os from sklearn.linear_model import LinearRegression # Import the learning algorithm number_of_cells = 21 for cell_number in xrange(number_of_cells): print '********************************************' print 'cell number', cell_number #################### # Load the data #################### folder = './data/' #cell_number = 8 cell = '_cell_' + str(cell_number) quality = '_3000_21_' stimuli_type = 'SparseNoise' #stimuli_type = 'DenseNoise' file_format = '.pickle' filename_vm = folder + 'vm' + cell + quality + stimuli_type + file_format filename_images = folder + 'images'+ quality + stimuli_type + file_format print 'Stimuli Type', stimuli_type # Save figures save_figures = False f = open(filename_vm,'rb') vm = cPickle.load(f) f = open(filename_images,'rb' ) ims = cPickle.load(f) ims = ims / 100 ims = ims - 0.5 #ims = ims - 50.0 ims2 = ims**2 Nside = ims.shape[2] f.close() ##########################33 # ##########################33 #Scale and size values dt = 1.0 #milliseconds dim = 21.0 # milliseconds dh = 5.0 #milliseconds kernel_duration = 150 # ms kernel_size = int(kernel_duration / dh) # Scale factors input_to_image = dt / dim # Transforms input to image kernel_to_input = dh / dt # Transforms kernel to input image_to_input = dim / dt ## Input preprocesing vm = downsample(vm,dt) # Take the data that is going to be use from the total data #Ntotal = 2 * 10 ** (4) # Number of data to use Ntotal = vm.size percentage = 1.0 Ntotal = int(percentage * vm.size) # Take the minimum between the maximum and the choice Ntotal = np.min((Ntotal, vm.size)) V = vm[0:int(Ntotal)] vm = None # Liberate memory # Size of the training set as a percentage of the data alpha = 1 # training vs total Ntraining = int(alpha * Ntotal) # Construct the set of indexes (training, test, working) Ntest = 10000 remove_start = int(kernel_size * kernel_to_input) # Number of images in a complete kernel Ntest = np.min((Ntest, Ntotal - Ntraining)) # Take Ntest more examples to test, or the rest available working_indexes = np.arange(Ntotal) working_indexes = working_indexes.astype(int) training_indexes = np.arange(remove_start, Ntraining) test_indexes = np.arange(Ntraining,Ntraining + Ntest) test_indxes = test_indexes.astype(int) # Calculate kernel kernel_times = np.arange(kernel_size) kernel_times = kernel_times.astype(int) # Make the values indexes # Delay indexes delay_indexes = np.floor(kernel_times * kernel_to_input) delay_indexes = delay_indexes.astype(int) # Image Indexes image_indexes = np.zeros(working_indexes.size) image_indexes[working_indexes] = np.floor(working_indexes * input_to_image) image_indexes = image_indexes.astype(int) # Normalize the output mean = np.mean(V[training_indexes]) V = V - mean #std = np.std(V) #V = V / std #V = V / (np.max(V) - np.min(V)) #V = V / (np.max(np.abs(V))) ######################## # Calculate Regression ######################## # Number of parameters Nparameters = Nside*Nside*2 # Create a vector with the indexes of the elements after the image extract = np.arange(0, training_indexes.size, int(image_to_input), dtype=int) training_indexes = training_indexes[extract] # Initialize the kernels h1 = np.zeros((kernel_size, Nside, Nside)) h2 = np.zeros((kernel_size, Nside, Nside)) # Targets Y = V[training_indexes] # Create the training matrix X = np.zeros((training_indexes.size, Nparameters)) print 'X shape', X.shape print 'Y shape', Y.shape print 'file = ', filename_vm for tau, delay_index in enumerate(delay_indexes): # Create matrix X for i, index in enumerate(training_indexes): delay = image_indexes[index - delay_index] f1 = np.reshape(ims[delay, ...], Nside*Nside) f2 = np.reshape(ims2[delay, ...], Nside*Nside) X[i, :] = np.concatenate((f1,f2)) # Store matrix X #store_X(X, tau, filename) # Making the predictions predictor = LinearRegression(copy_X=False, fit_intercept=False) predictor.fit(X, Y) # Extract the parameters parameters = predictor.coef_ # Order them as squares h1_dis = parameters[0:Nparameters / 2] h2_dis = parameters[Nparameters / 2 :] # Store them h1[tau,...] = h1_dis.reshape(Nside,Nside) h2[tau,...] = h2_dis.reshape(Nside,Nside) ############ # Plotting ############ if save_figures: symmetric = 0 colorbar = True closest_square_to_kernel = int(np.sqrt(kernel_size)) ** 2 directory = './figures/' formating='.pdf' title = 'data_regresion_h1' + quality + stimuli_type save_filename = directory + title + formating plot_mutliplot_bilinear(closest_square_to_kernel, h1, colorbar=colorbar, symmetric=symmetric) figure = plt.gcf() # get current figure if remove_axis: #Remove axis for i in xrange(closest_square_to_kernel): figure.get_axes()[i].get_xaxis().set_visible(False) figure.get_axes()[i].get_yaxis().set_visible(False) figure.set_size_inches(16, 12) plt.savefig(save_filename, dpi = 100) os.system("pdfcrop %s %s" % (save_filename, save_filename)) plt.show() plot_mutliplot_bilinear(closest_square_to_kernel, h2, colorbar=colorbar, symmetric=symmetric) title = 'data_regresion_h2' + quality+ stimuli_type save_filename = directory + title + formating figure = plt.gcf() # get current figure if remove_axis: # Remove axis for i in xrange(closest_square_to_kernel): figure.get_axes()[i].get_xaxis().set_visible(False) figure.get_axes()[i].get_yaxis().set_visible(False) figure.set_size_inches(16, 12) plt.savefig(save_filename, dpi = 100) os.system("pdfcrop %s %s" % (save_filename, save_filename)) plt.show() ############### # Saving ############### store_kernel_numpy(kernel_size, h1, h2, cell_number, stimuli_type)
{ "repo_name": "h-mayorquin/M2_complexity_thesis", "path": "Analysis/regresion_simulation_total.py", "copies": "1", "size": "6874", "license": "bsd-2-clause", "hash": 5599904462026160000, "line_mean": 31.2723004695, "line_max": 105, "alpha_frac": 0.5768111725, "autogenerated": false, "ratio": 3.6680896478121663, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9515786212379953, "avg_score": 0.0458229215864425, "num_lines": 213 }
from functions import * from grid import * from mob import * from tiles import * import pyglet RES_PATH = "resources/" class Game(): """Game session.""" def __init__(self, window): self.debug = window.debug self.window = window # Need to keep track of the game window # Lists of game objects self.mobs = [] # Enemy mob sprite objects self.mob_count = 0 # This serve as mob's id self.towers = [] # Tower sprite objects self.available_towers = { "1": 10, "2": 25, "3": 40, "4": 90, } self.selected_mouse = None # Holds the object mouse is dragging self.dragging = False # If an object is currently being dragged self.mouse_drag_tower = None self.active_tower = None # List of highlighted items self.autospawn = False self.loaded = False # If game is loaded self.paused = True # Game starts off in a paused state self.lives = 10 # Economy self.gold = 0 # Players "wallet" self.ai_gold = 0 # Gold used to spawn mobs by AI self.total_value = 0 # To be used later for adaptive difficulty # Pathfinding stuff self.pf_queue = [] self.pf_clusters = [] # Specifies how the game grid will be, and calculates the offset # self.generateGridSettings() # player = pyglet.media.Player() # sound = pyglet.media.load('../resources/mus1.ogg') # player.queue(sound) # # keep playing for as long as the app is running (or you tell it to stop): # player.eos_action = pyglet.media.Player.EOS_LOOP # player.play() def newGame(self, level="default"): print("Starting a new game.") # Display load screen self.window.mainmenu = None # Kills the menu self.window.loading = True pyglet.gl.glClear(pyglet.gl.GL_COLOR_BUFFER_BIT) self.window.render(0) self.window.flip() # Remove old stuff from game window self.window.flushWindow() # Generates grid parameters for game instance self.tiles_no_build = [] self.tiles_no_walk = [] self.generateGridSettings() self.grid = Grid(self) self.window.tile_renderer.update_offset() # Create particle emitters self.window.addParticleEmitters() # Lists of game objects for m in self.mobs: m.debuff_list = [] self.mobs = [] # Enemy mob sprite objects self.mob_count = 0 # This serve as mob's id for t in self.towers: t.target = None self.goal, self.spawn = None, None self.towers = [] # Tower sprite objects self.window.animations = [] self.selected_mouse = None self.dragging = False self.highlighted = [] self.active_tower = None self.mouse_drag_tower = None self.pf_queue = [] self.gold = 25 self.ai_gold = 0 self.ai_flat_income = 0 try: pyglet.clock.unschedule(self.ai_income) except: pass try: pyglet.clock.unschedule(self.autospawn_balanced) except: pass pyglet.clock.schedule_interval( self.ai_income, 10.0 ) pyglet.clock.schedule_interval( self.autospawn_balanced, 0.25 ) self.lives = 10 pyglet.clock.unschedule(self.autospawn_random) pyglet.clock.schedule_interval(self.pathFinding, 1.0/60.0) # Autospawn random mob every second self.autospawn = False self.grid.update() # Adding buttons to UI for b in ("1", "2", "3", "4", "gold_icon"): self.window.userinterface.add_button(b) self.window.userinterface.add_text("gold") self.window.loading = False self.loaded = True self.paused = False def generateGridSettings(self): """ These control the grid that is the game window """ tiles = TiledRenderer(self.window, RES_PATH + "map1.tmx") mw = tiles.tmx_data.width mh = tiles.tmx_data.height self.grid_dim = (mw, mh) w, h, gm = self.window.width, self.window.height, 0 self.grid_margin = gm ssize = tiles.tmx_data.tilewidth self.squaresize = ssize self.window.offset_x = (w - self.grid_dim[0] * (ssize + gm)) // 2 self.window.offset_y = (h - self.grid_dim[1] * (ssize + gm)) // 2 self.window.tile_renderer = tiles def updateGridSettings(self): w, h, gm, ssize = self.window.width, self.window.height, \ self.grid_margin, self.squaresize self.window.offset_x = (w - self.grid_dim[0] * (ssize + gm)) // 2 self.window.offset_y = (h - self.grid_dim[1] * (ssize + gm)) // 2 def createGridIndicators(self): self.window._rectangles = pyglet.graphics.vertex_list( 4, 'v2i' ) self.window._rectangles_path = pyglet.graphics.vertex_list( 4, 'v2i' ) self.window.rectangles = [] self.window.rectangles_path = [] grid = [] path = [] for p in self.grid.t_grid: grid.append(p) for p in self.grid.path: try: grid.remove(p) path.append(p) except ValueError: pass for p in grid: pos = self.window.get_windowpos(p[0], p[1]) x, y = pos ss = self.squaresize - 2 rectangle = create_rectangle(x, y, ss, ss) self.window.rectangles.append(rectangle) for p in path: pos = self.window.get_windowpos(p[0], p[1]) x, y = pos ss = self.squaresize - 6 rectangle = create_rectangle(x, y, ss, ss) self.window.rectangles_path.append(rectangle) batch = self.window.batches["fg2"] for r in self.window.rectangles: # vertex_list = pyglet.graphics.vertex_list(4, # ('v2i', r), # ('c3B', [128, 128, 255, 80] * 4) # ) self.window._rectangles = batch.add( 4, pyglet.graphics.gl.GL_QUADS, None, ('v2i', r), ) batch = self.window.batches["fg3"] for r in self.window.rectangles_path: self.window._rectangles_path = batch.add( 4, pyglet.graphics.gl.GL_QUADS, None, ('v2i', r), ) def pathFinding(self, dt, limit=1): if len(self.pf_queue) > 0: if len(self.pf_queue) >= 60: limit *= 2 if self.debug: print("Calculating paths for pf_queue.") print("Length of queue: {0}.".format(len(self.pf_queue))) count = 0 for m in self.pf_queue: if count == limit: break m.updateTarget() self.pf_queue.remove(m) count += 1 # for m in self.mobs: # if m.state == "stalled": # m.updateState() def place_tower(self, t, x, y, new=False): """Positions tower and updates game state accordingly.""" placed = False grid = self.grid dist = self.window.height // 10 # Range to check for available square if t.price <= self.gold: for g in grid.t_grid: if not g == grid.goal or g == grid.start: if x and y: gx = self.window.get_windowpos(g[0], g[1])[0] gy = self.window.get_windowpos(g[0], g[1])[1] if get_dist(gx, gy, x, y) < dist: dist = get_dist(gx, gy, x, y) placed = False if dist <= self.squaresize: placed = True new_g = g new_rg = (gx, gy) if placed: self.gold -= t.price t.selected = False t.updatePos(new_rg[0], new_rg[1], new_g[0], new_g[1]) if new: self.towers.append(t) print("Towers: {0}".format(len(self.towers))) update = False if new_g in grid.path: update = True else: for p in grid.path: if new_g in get_diagonal( grid.w_grid, p[0], p[1] ): update = True break elif new_g in get_neighbors( grid.w_grid, p[0], p[1] ): update = True break if update: for m in self.mobs: if m not in self.pf_queue: if check_path(m, grid.w_grid, new_g): self.pf_queue.append(m) grid.update(new=update) # self.pathFinding(limit=100) if self.debug: print("New path for grid: {0}".format(update)) if self.debug: print("Tower placed at [{0},{1}]".format(new_g[0], new_g[1])) elif t in self.towers: self.towers.remove(t) grid.update(new=False) else: self.active_tower = None self.mouse_drag_tower = None self.selected_mouse = None def autospawn_random(self, dt): """Spawns a random mob""" if not self.paused: choice = random.randint(0, 2) if choice: mob = Mob(self, "YAY") else: mob = Mob1W(self, "YAY") self.mobs.append(mob) def autospawn_balanced(self, dt): if not self.paused and self.ai_gold > 0: mob_choices = 9 choice = random.randint(0, mob_choices - 1) if choice < mob_choices - 1 and len(self.mobs) >= 100: choice += 2 mob = None if choice == 0: mob = Mob(self, "YAY") elif choice == 1: mob = Mob1W(self, "YAY") elif choice == 2: mob = Mob1E(self, "YAY") elif choice == 3: mob = Mob1R(self, "YAY") elif choice == 4: mob = Mob1A(self, "YAY") elif choice == 5: mob = Mob1S(self, "YAY") elif choice == 6: mob = Mob1D(self, "YAY") elif choice == 7: mob = Mob1F(self, "YAY") elif choice == 8: mob = Mob1Z(self, "YAY") if mob and mob.bounty * 2 <= self.ai_gold: self.mobs.append(mob) self.ai_gold -= mob.bounty * 2 def ai_income(self, dt): self.ai_gold += self.ai_flat_income self.ai_flat_income += 1 self.ai_gold += (self.get_total_value() + self.gold) // 10 print self.ai_gold def updateState(self): for t in self.towers: if not t.target: # if tower has no target i = random.randrange(0, 1) for m in self.mobs: if(m.move_type in t.target_types): dist = get_dist(m.x, m.y, t.x, t.y) if dist <= t.range: if i == 0: t.target = m break else: # if tower has a target, do something dist = get_dist(t.target.x, t.target.y, t.x, t.y) if dist > t.range: t.target = None if t.target not in self.mobs: t.target = None if t.target: if t.target.state == "alive": rads = get_angle(t.x, t.y, t.target.x, t.target.y) t.setAngle(rads) t.doDamage(t.target) # Do damage if t.target.state == "dead": t.target = None t.resetCD() for m in self.mobs: m.updatePos() # Update movement m.updateState() # Update mob state, e.g. "dead", "alive" if self.gold > 999: # Maximum amount of gold self.gold = 999 if self.lives <= 0: self.newGame() def leaking(self): self.lives -= 1 self.window.play_sfx("pluck") def get_total_value(self): value = 0 for t in self.towers: value += t.price return value # def generateGridIndicators(self): # """ Generates the squares that indicates available blocks """ # w = self.squaresize # points = [] # rects = [] # for p in self.grid.w_grid: # wp = self.window.get_windowpos(p[0], p[1]) # x = wp[0] - w // 2 # y = wp[1] - w // 2 # points.append(wp[0]) # points.append(wp[1]) # r_points = [x, y, x + w, y, x + w, y + w, x, y + w] # rects = rects + r_points
{ "repo_name": "NiclasEriksen/py-towerwars", "path": "deploy/src/game.py", "copies": "1", "size": "13534", "license": "cc0-1.0", "hash": -6452789199649710000, "line_mean": 32.7506234414, "line_max": 84, "alpha_frac": 0.4759125166, "autogenerated": false, "ratio": 3.8059617547806526, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4781874271380652, "avg_score": null, "num_lines": null }
from functions import * from plot_functions import plot_mutliplot_bilinear from analysis_functions import * import numpy as np import cPickle import matplotlib.pyplot as plt import os from time import localtime import scipy.io from sklearn.linear_model import LinearRegression # Import the learning algorithm #################### # Load and process the data #################### ## Load number_of_files = 6 directory = './cyrill/' file_name = 'EP' extension = '.mat' stimuli_type = 'SparseNoise' # Comment the one that is not going to be used stimuli_type = 'DenseNoise' # Save things or not save_figures = True # Save the figures if True save_files = False # Save the files if True remove_axis = False # Remove axis if True # Save the files to a list files = [] for i in xrange(number_of_files): file_to_retrieve = directory + file_name + str(i+1) + extension files.append(scipy.io.loadmat(file_to_retrieve)) # Kernel data and intialization dh = 4.0 #milliseconds kernel_duration = 150 # ms kernel_size = int(kernel_duration / dh) # Empty lists to concatenate working_indexes_t = [] training_indexes_t = [] image_indexes_t = [] V_t = [] ims_t = [] temporal_image = [] Nlast = 0 for i, file_to_retrieve in enumerate(files): data = file_to_retrieve.values() # Import the data ims = data[4] # The arrays with the images ims = np.transpose(ims) ims = ims / 2.0 # Scale ims = ims - 0.5 # Center ims2 = ims**2 Nside = ims.shape[2] frame_times = data[0] # The times at which the frames start diff_frame = np.diff(frame_times, axis=0) # This calculate the duration of each frame vm = data[2] # Extracts voltage ## Pre-process the signal # sampling interval sampling_time_interval = 0.102 # Obtained from Cyrills, experimental value factor = 10 # vm = downsample(vm, factor) # Sample down the signal by factor first_image = int( frame_times[0] / (factor * sampling_time_interval)) # time of the first image last_image = int( (frame_times[-1] + np.mean(diff_frame)) / (factor * sampling_time_interval)) last_image = int( (frame_times[-1] ) / (factor * sampling_time_interval)) # time of the last image vm = vm[first_image:last_image] # Takes only the voltage that corresponds to images ################ ## Data parameters ################ #Scale and size values dt = sampling_time_interval * factor # Sampling time interval (ms) dim = np.mean(diff_frame) # Duration of each image (ms) # Scale factors input_to_image = dt / dim # Transforms input to image kernel_to_input = dh / dt # Transforms kernel to input image_to_input = dim / dt # transforms imagen to input Ntotal = vm.size # Number of data to use (must be equal or less than vm.size) #Take the minimum between the maximum and the choice Ntotal = np.min((Ntotal, vm.size)) V = vm[0:Ntotal] #Size of the training set as a percentage of the data alpha = 1 # training vs total Ntraining = int(alpha * Ntotal) #Construct the set of indexes (training, test, working) remove_start = int(kernel_size * kernel_to_input) # Number of images in a complete kernel working_indexes = np.arange(Ntotal) training_indexes = np.arange(remove_start, Ntraining) #Calculate kernel kernel_times = np.arange(kernel_size) kernel_times = kernel_times.astype(int) # Make the values indexes #Delay indexes delay_indexes = np.floor(kernel_times * kernel_to_input) delay_indexes = delay_indexes.astype(int) #Image Indexes image_indexes = np.zeros(working_indexes.size) for k, index in enumerate(working_indexes): index = index * dt + frame_times[0] #Transform to ms aux = np.where(frame_times > index)[0] # Indexes of the frame times thata aux = np.min(aux) image_indexes[k] = int(aux) - 1 # image_indexes = np.zeros(working_indexes.size) # image_indexes[working_indexes] = np.floor(working_indexes * input_to_image) # image_indexes = image_indexes.astype(int) # # Concatenate print i if i > 0: image_indexes_t = np.concatenate((image_indexes_t, image_indexes + ims_t.shape[0] )) ims_t = np.concatenate((ims_t, ims), axis=0) working_indexes_t = np.concatenate((working_indexes_t, working_indexes + Nlast)) training_indexes_t = np.concatenate((training_indexes_t, training_indexes + Nlast )) V_t = np.concatenate((V_t, vm)) else: ims_t = ims working_indexes_t = np.concatenate((working_indexes_t, working_indexes)) training_indexes_t = np.concatenate((training_indexes_t, training_indexes)) image_indexes_t = np.concatenate((image_indexes_t, image_indexes)) V_t = np.concatenate((V_t, vm)) Nlast += Ntotal # show files increase print 'last image index', image_indexes_t[-1] print 'image size ', ims_t.shape[0] print 'V', V_t.shape, print 'image_indexes', image_indexes_t.shape print 'training_indexes', training_indexes_t.shape print 'working_indexes', working_indexes_t.shape print '------------------------------------------' # Erase unused references ims = None vm = None ims2 = None V = None training_indexes = None working_indexes = None image_indexes = None files = None # Make things indexes training_indexes = training_indexes_t.astype(int) image_indexes = image_indexes_t.astype(int) working_indexes = working_indexes_t.astype(int) # take out the spikes #treshold = -60 #V_t [ V_t > treshold] = treshold mean_t = np.mean(V_t) V_t = V_t - mean_t V = V_t ims = ims_t ims2 = ims ** 2 ims_t = None V_t= None ######################## # Calculate Regression ######################## # Number of parameters Nparameters = Nside*Nside*2 # Create a vector with the indexes of the elements after the image extract = np.arange(0, training_indexes.size, int(image_to_input), dtype=int) training_indexes = training_indexes[extract] # Initialize the kernels h1 = np.zeros((kernel_size, Nside, Nside)) h2 = np.zeros((kernel_size, Nside, Nside)) # Targets Y = V[training_indexes] # Create the matrix of training X = np.zeros((training_indexes.size, Nparameters)) print 'X shape', X.shape print 'Y shape', Y.shape for tau, delay_index in enumerate(delay_indexes): print 'tau', tau print 'Creating the matrix X' for i, index in enumerate(training_indexes): delay = image_indexes[index - delay_index] f1 = np.reshape(ims[delay, ...], Nside*Nside) f2 = np.reshape(ims2[delay, ...], Nside*Nside) X[i, :] = np.concatenate((f1,f2)) predictor = LinearRegression(copy_X=False, fit_intercept=False) predictor.fit(X, Y) ## Order parameters parameters = predictor.coef_ h1_dis = parameters[0:Nparameters / 2] h2_dis = parameters[Nparameters / 2 :] h1[tau,...] = h1_dis.reshape(Nside,Nside) h2[tau,...] = h2_dis.reshape(Nside,Nside) ############ # Plotting ############ if save_figures: symmetric = 0 colorbar = False closest_square_to_kernel = int(np.sqrt(kernel_size)) ** 2 directory = './figures/' formating='.pdf' title = 'real_regresion_h1' save_filename = directory + title + formating plot_mutliplot_bilinear(closest_square_to_kernel, h1, colorbar=colorbar, symmetric=symmetric) figure = plt.gcf() # get current figure if remove_axis: # Remove axis for i in xrange(closest_square_to_kernel): figure.get_axes()[i].get_xaxis().set_visible(False) figure.get_axes()[i].get_yaxis().set_visible(False) figure.set_size_inches(16, 12) plt.savefig(save_filename, dpi = 100) os.system("pdfcrop %s %s" % (save_filename, save_filename)) plt.show() plot_mutliplot_bilinear(closest_square_to_kernel, h2, colorbar=colorbar, symmetric=symmetric) title = 'real_regresion_h2' save_filename = directory + title + formating figure = plt.gcf() # get current figure if remove_axis: # Remove axis for i in xrange(closest_square_to_kernel): figure.get_axes()[i].get_xaxis().set_visible(False) figure.get_axes()[i].get_yaxis().set_visible(False) figure.set_size_inches(16, 12) plt.savefig(save_filename, dpi = 100) os.system("pdfcrop %s %s" % (save_filename, save_filename)) plt.show() ############ # Saving ############ if save_figures: directory = './kernels/' formating='.npy' title = 'real_regresion_h1' save_filename1 = directory + stimuli_type + title + formating np.save(save_filename1, h1) directory = './kernels/' formating='.npy' title = 'real_regresion_h2' save_filename2 = directory + stimuli_type + title + formating np.save(save_filename2, h2)
{ "repo_name": "h-mayorquin/M2_complexity_thesis", "path": "Analysis/regresion_experiment.py", "copies": "1", "size": "9063", "license": "bsd-2-clause", "hash": 1894446164800087600, "line_mean": 28.9108910891, "line_max": 103, "alpha_frac": 0.6301445437, "autogenerated": false, "ratio": 3.3842419716206122, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4514386515320612, "avg_score": null, "num_lines": null }
from .functions import * from pytaskflow.taskflow_engine import WorkFlow, Task def get_error_task(): t_err = Task(task_name='Error Task') t_err.register_function(function=ErrorMessageFunction(), success_task=None, err_task=None) return t_err def get_workflow(): t4 = Task(task_name='Task 3: Dump All Variables') t4.register_function(function=DumpResultObj(), success_task=None, err_task=None) t3 = Task(task_name='Task 2: Calculate Sum Total of a List of Numbers') t3.register_function(function=CalcSumOfListOfNumbers(), success_task=t4, err_task=get_error_task()) t2 = Task(task_name='Task Debug:') t2.register_function(function=DumpResultObj(), success_task=t3, err_task=get_error_task()) t1 = Task(task_name='Task 1: Generated List of Numbers') t1.register_function(function=GenerateRandomNumberAndAddToList(), success_task=t2, err_task=get_error_task(), globals_dict={'GenerateRandomNumberAndAddToListTask': t1}) return WorkFlow(workflow_name='Example Workflow', starter_task=t1) # EOF
{ "repo_name": "nicc777/pytaskflow", "path": "examples/example01/workflow_factory.py", "copies": "1", "size": "1043", "license": "bsd-3-clause", "hash": 901864258894970800, "line_mean": 44.3913043478, "line_max": 172, "alpha_frac": 0.7344199425, "autogenerated": false, "ratio": 3.269592476489028, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45040124189890285, "avg_score": null, "num_lines": null }
from functions import * import argparse def updateStart(db, gene_id, newStart, rev_comp): cur = db.cursor() if rev_comp == False: cur.execute("UPDATE gene SET start = " + str(newStart) + ", adjusted = 1 WHERE id = " + str(gene_id)) else: cur.execute("UPDATE gene SET end = " + str(newStart) + ", adjusted = 1 WHERE id = " + str(gene_id)) db.commit() def findBestStart(db, gene, potentialStarts, ideal_move_distance): print potentialStarts if gene['rev_comp']: check = gene['end'] else: check = gene['start'] imd = ideal_move_distance * 3 diffs = [np.abs(s - imd) for s in potentialStarts] return potentialStarts[np.argmax(diffs)] def tooLongForwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['start'] + (3 * i) # increase our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] # codon is going forward print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "***far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "***on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooLongBackwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['start'] - (3 * i) # decrease our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] # codon is going backward codon = codon[::-1] # reverse the codon print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooLongForwardRevComp(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['end'] + (3 * i) - 2 # increase our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] # codon is going forward print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "***far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "***on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooLongBackwardRevComp(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['end'] - (3 * i) - 2 # decrease our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] # codon is going backward codon = codon[::-1] # reverse the codon print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooLong(db, gene, ideal_move_distance, start_codons, stop_codons,revcomp_start_codons,revcomp_stop_codons): if gene['rev_comp'] == False: if gene['start'] < gene['end']: print "Forward" return tooLongForwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons) elif gene['start'] > gene['end']: print "Backward" return tooLongBackwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons) else: if gene['start'] < gene['end']: print "Forward" return tooLongForwardRevComp(db, gene, ideal_move_distance, revcomp_start_codons, revcomp_stop_codons) elif gene['start'] > gene['end']: print "Backward" return tooLongBackwardRevComp(db, gene, ideal_move_distance, revcomp_start_codons, revcomp_stop_codons) def tooShortForwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['start'] - (3 * i) # decrease our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooShortBackwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['start'] + (3 * i) # increase our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] codon = codon[::-1] # reverse the codon print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooShortForwardRevComp(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['end'] - (3 * i) - 2 # decrease our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooShortBackwardRevComp(db, gene, ideal_move_distance, start_codons, stop_codons): # Init bestGeneStart farBestGeneStart = None closeBestGeneStart = None # Run through all the potential starts for i in xrange(1,ideal_move_distance*2): # doubled to we have equal search space on both sides currentStart = gene['end'] + (3 * i) - 2 # increase our start 3 at a time phage = get_phage(db, gene['phage_id']) phageGenome = phage['seq'] codon = phageGenome[currentStart:currentStart+3] codon = codon[::-1] # reverse the codon print codon if codon in stop_codons: print "Found stop codon at {}".format(currentStart) break elif codon in start_codons and i > ideal_move_distance: print "far" farBestGeneStart = currentStart break elif codon in start_codons and i <= ideal_move_distance: print "on or before" closeBestGeneStart = currentStart return closeBestGeneStart, farBestGeneStart def tooShort(db, gene, ideal_move_distance, start_codons, stop_codons): if gene['rev_comp'] == False: if gene['start'] < gene['end']: print "Forward" return tooShortForwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons) elif gene['start'] > gene['end']: print "Backward" return tooShortBackwardNormal(db, gene, ideal_move_distance, start_codons, stop_codons) else: if gene['start'] < gene['end']: print "Forward" return tooShortForwardRevComp(db, gene, ideal_move_distance, revcomp_start_codons, revcomp_stop_codons) elif gene['start'] > gene['end']: print "Backward" return tooShortBackwardRevComp(db, gene, ideal_move_distance, revcomp_start_codons, revcomp_stop_codons) # makes the best possible adjustments for a given cluster, aligning any genes that do not belong to def adjust_cluster(db,cluster,golden_phage_id,start_codons,stop_codons): #first we need to make a list of all the golden phage proteins that are in this create_cluster golden_phages = get_golden_phages(db) golden_genes = get_golden_genes(golden_phages, cluster) print golden_genes.values() print golden_phages #print golden_genes if len(golden_genes) == 0: #make sure there is at least one gene from the golden phage in the cluster return for gene in cluster: if gene['phage_id'] not in golden_phages: potentialStarts = set() # Because if we have muliple golds we will have many different starts to try? print print "New Gene" possible_adjustments = [] for index, gold_ids in enumerate(golden_genes.values()): print index, gold_ids for gold_id in gold_ids: blastp_hit = None for hit in gene['hits']: #find hit in gene for that gold_id if hit['subject_id'] == gold_id: blastp_hit = hit break if blastp_hit is not None: # if we found a hit for that gene, continue #print "Gene", gene['id'], "and gene", gold_id, "has hit", blastp_hit golden_start = blastp_hit['subject_start'] gene_start = blastp_hit['query_start'] # our gene is too short and we need to move the start upstream if gene_start == 1 and golden_start == 1: print "They are already perfectly aligned!" elif gene_start == 1: print "Too Short" ideal_move_distance = golden_start - gene_start newCloseStart, newFarStart = tooShort(db, gene, ideal_move_distance, start_codons, stop_codons,revcomp_start_codons,revcomp_stop_codons) if newCloseStart != None: potentialStarts.add(newCloseStart) if newFarStart != None: potentialStarts.add(newFarStart) # our gene is too long and we need to trim it down elif golden_start == 1: print "Too Long" ideal_move_distance = gene_start - golden_start newCloseStart, newFarStart = tooLong(db, gene, ideal_move_distance, start_codons, stop_codons,revcomp_start_codons,revcomp_stop_codons) ######## Just to debug ##################### print "Starts:", newCloseStart, newFarStart print "Original:", gene['start'] ################################### if newCloseStart != None: potentialStarts.add(newCloseStart) if newFarStart != None: potentialStarts.add(newFarStart) # right now we do nothing... else: print "Neither one starts at 1..." else: print "Gene", gene['id'], "has no blastp hit for golden gene", gold_id, gene['hits'] if potentialStarts: # if set is not empty bestStart = findBestStart(db, gene, potentialStarts, ideal_move_distance) updateStart(db, gene['id'], bestStart, gene['rev_comp']) Uncomment when ready ############################################################################################################### parser = argparse.ArgumentParser() parser.add_argument("--clustalo_cutoff", help="Minimum percent identity when clustering", default=32.5) parser.add_argument("--blastp_cutoff", help="Minimum e-value when clustering", default=1e-35) args = parser.parse_args() # Hard coded for dev start_codons = ['ATG','GTG','TTG'] #CCG revcomp_start_codons = ['CAT', 'CAC', 'CAA'] stop_codons = ['TAG', 'TAA', 'TGA'] revcomp_stop_codons = ['CTA', 'TTA', 'TCA'] cluster_id = 17 db = connect_db("geneysis.db") cluster = get_cluster(db, cluster_id, args) golden_phage_id = 5 adjust_cluster(db,cluster,golden_phage_id,start_codons,stop_codons,revcomp_start_codons,revcomp_stop_codons)
{ "repo_name": "pjtatlow/geneysis", "path": "python/practiceCode.py", "copies": "1", "size": "15427", "license": "mit", "hash": 4554757448240779000, "line_mean": 41.6160220994, "line_max": 164, "alpha_frac": 0.601737214, "autogenerated": false, "ratio": 3.8166749134092033, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4918412127409203, "avg_score": null, "num_lines": null }
from functions import * import sys, os #This file contains all of the injection and retrieval algorithms used def xthPixelInject(args = None): #args should be [pixList, newPixList, intFiList, [Relevant CLI Args as list]] pixList = args[0] newPixList = args[1] intFiList = args[2] xth = int(args[3][0]) #The only arg this accepts is X valIndex = 0 byteNum = len(intFiList) for n in range(4, len(pixList) - 1): x, y, z = pixList[n] if(xthPattern(n, xth)): #Write the data to a pixel if(valIndex < len(intFiList)): baseColor = averageColor(pixList[n - 1], pixList[n + 1]) dataColor = colorTupleFromValue(intFiList[valIndex], 7) finalColor = injectDataColorBaseX(baseColor, dataColor, 7) newPixList.append(finalColor) valIndex += 1 sys.stdout.write("\r" + str(int((valIndex/byteNum) * 100)) + "% Complete") sys.stdout.flush() else: newPixList.append((x, y, z)) else: newPixList.append((x, y, z)) print("!") #To satisfy my autism return newPixList def xthPixelRetrieve(args = None, silent = False):#args should be [pixList, byteNum, [Relevant CLI Args as list]] pixList = args[0] byteNum = args[1] xth = args[2][0] f = [] valIndex = 0 for n in range(4, len(pixList) - 1): try: x, y, z = pixList[n] if(valIndex >= byteNum): if(not silent): print("\n" + str(byteNum) + " bytes retrieved.") break if(xthPattern(n, xth)): #Extract data from a pixel baseColor = averageColor(pixList[n - 1], pixList[n + 1]) dataColor = retrieveDataColorBaseX((x, y, z), baseColor, 7) data = colorTupleBaseXToVal(dataColor, 7) f.append(data) valIndex += 1 if(not silent): sys.stdout.write("\r" + str(int((valIndex/byteNum) * 100)) + "% Complete") sys.stdout.flush() else: pass except: print("\nERROR: Could not retrieve bytes.") print(str(valIndex) + "/" + str(byteNum) + " bytes retrieved before Error.") os._exit() return f ##################################################### def inColorInject(args = None): #args should be [pixList, newPixList, intFiList, [Relevant CLI Args as list]] pixList = args[0] newPixList = args[1] intFiList = args[2] color = args[3][0] #The only arg this accepts is X dist = int(args[3][1]) valIndex = 0 byteNum = len(intFiList) for n in range(4, len(pixList) - 1): x, y, z = pixList[n] baseColor = averageColor(pixList[n - 1], pixList[n + 1]) if(inColorPattern(n, baseColor, [color, dist])): #Write the data to a pixel if(valIndex < len(intFiList)): dataColor = colorTupleFromValue(intFiList[valIndex], 7) finalColor = injectDataColorBaseX(baseColor, dataColor, 7) newPixList.append(finalColor) valIndex += 1 sys.stdout.write("\r" + str(int((valIndex/byteNum) * 100)) + "% Complete") sys.stdout.flush() else: newPixList.append((x, y, z)) else: newPixList.append((x, y, z)) print("!") #To satisfy my autism return newPixList def inColorRetrieve(args = None, silent = False):#args should be [pixList, byteNum, [Relevant CLI Args as list]] pixList = args[0] byteNum = args[1] color = args[2][0] dist = args[2][1] f = [] valIndex = 0 for n in range(4, len(pixList) - 1): try: x, y, z = pixList[n] baseColor = averageColor(pixList[n - 1], pixList[n + 1]) if(valIndex >= byteNum): if(not silent): print("\n" + str(byteNum) + " bytes retrieved.") break if(inColorPattern(n, baseColor, [color, dist])): #Extract data from a pixel dataColor = retrieveDataColorBaseX((x, y, z), baseColor, 7) data = colorTupleBaseXToVal(dataColor, 7) f.append(data) valIndex += 1 if(not silent): sys.stdout.write("\r" + str(int((valIndex/byteNum) * 100)) + "% Complete") sys.stdout.flush() else: pass except: print("\nERROR: Could not retrieve bytes.") print(str(valIndex) + "/" + str(byteNum) + " bytes retrieved before Error.") os._exit(1) return f
{ "repo_name": "jjsullivan5196/steganosaurus", "path": "algorithms.py", "copies": "1", "size": "3923", "license": "mit", "hash": 2191686948455019500, "line_mean": 31.974789916, "line_max": 113, "alpha_frac": 0.6393066531, "autogenerated": false, "ratio": 2.7882018479033404, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39275085010033406, "avg_score": null, "num_lines": null }
from .functions import * def locatePlate(img, file_path, plot=False): scale, img_resized = resizeImage(img) regions = getRegions(img_resized) regions_filtered = filterRegions(img_resized, regions) if len(regions_filtered) == 1: points = refineBoundaries(img_resized, regions_filtered[0]) points = [(int(x / scale), int(y / scale)) for (x,y) in points] else: points = [(0, 0), (0, 0), (0, 0), (0, 0)] if plot is True: from itertools import izip from .utils import createPlot from .utils import checkPlateSize from .utils import drawQuadrilateralRegion from .utils import drawQuadrilateralRegion from .utils import showPlot ax = createPlot(img_resized, file_path) ann = np.loadtxt(file_path.replace('.jpg', '.txt'), dtype=str, delimiter=',') if ann.ndim == 1: ground_truth = [(int(x), int(y)) for x, y in izip(* [iter(ann[0:8])] * 2)] # checkPlateSize(img_resized, scale, ground_truth) drawQuadrilateralRegion(ax, ground_truth, scale, 'green') # drawRectangleRegions(ax, regions, 'yellow') # drawRectangleRegions(ax, regions_filtered, 'orange') drawQuadrilateralRegion(ax, points, scale, 'red') showPlot() return points
{ "repo_name": "allansp84/license-plate", "path": "modules/localization/localization/main.py", "copies": "1", "size": "1316", "license": "bsd-3-clause", "hash": 7536828573562078000, "line_mean": 37.7058823529, "line_max": 86, "alpha_frac": 0.6223404255, "autogenerated": false, "ratio": 3.556756756756757, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46790971822567573, "avg_score": null, "num_lines": null }
from functions import * g.startbuild = datetime.datetime.now() logger = logging.getLogger('neuromodulation') logger.debug("* * * Building layers") build_model() logger.debug("* * * Connecting layers in columns") for column in range(column_number): print "COLUMN {0}".format(column) ''' L2 ''' # for Glu connect(Cortex[L2][column][Glu], Cortex[L2][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L2_to_L2) connect(Cortex[L2][column][Glu], Cortex[L2][column][GABA], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L2_to_L2) connect(Cortex[L2][column][Glu], Cortex[L3][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L2_to_L3) connect(Cortex[L2][column][Glu], Cortex[L5A][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L2_to_L5A) connect(Cortex[L2][column][Glu], Cortex[L5B][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L2_to_L5B) # for GABA connect(Cortex[L2][column][GABA], Cortex[L2][column][Glu], neurotransmitter=GABA, weight_coef=1.5) ''' L3 ''' #connect(Cortex[L3][column][Glu], Cortex[L2][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L3_to_L2) connect(Cortex[L3][column][Glu], Cortex[L3][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L3_to_L3) connect(Cortex[L3][column][Glu], Cortex[L3][column][GABA], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L3_to_L3) connect(Cortex[L3][column][Glu], Cortex[L5A][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L3_to_L5A) #connect(Cortex[L3][column][Glu], Cortex[L5B][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L3_to_L5B) # for GABA connect(Cortex[L3][column][GABA], Cortex[L3][column][Glu], neurotransmitter=GABA, weight_coef=1.5) ''' L4 ''' # for Glu connect(Cortex[L4][column][Glu], Cortex[L2][column][Glu], neurotransmitter=Glu, weight_coef=0.6, conn_prob=L4_to_L2) connect(Cortex[L4][column][Glu], Cortex[L3][column][Glu], neurotransmitter=Glu, weight_coef=0.6, conn_prob=L4_to_L3) connect(Cortex[L4][column][Glu], Cortex[L4][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L4_to_L4) connect(Cortex[L4][column][Glu], Cortex[L4][column][GABA], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L4_to_L4) connect(Cortex[L4][column][Glu], Cortex[L5A][column][Glu], neurotransmitter=Glu, weight_coef=0.6, conn_prob=L4_to_L5A) connect(Cortex[L4][column][Glu], Cortex[L5B][column][Glu], neurotransmitter=Glu, weight_coef=0.6, conn_prob=L4_to_L5B) # for GABA connect(Cortex[L4][column][GABA], Cortex[L4][column][Glu], neurotransmitter=GABA, weight_coef=1.5) ''' L5A ''' # for Glu connect(Cortex[L5A][column][Glu], Cortex[L2][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5A_to_L2) connect(Cortex[L5A][column][Glu], Cortex[L3][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5A_to_L3) connect(Cortex[L5A][column][Glu], Cortex[L4][column][Glu], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L5A_to_L4) connect(Cortex[L5A][column][Glu], Cortex[L5A][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L5A_to_L5A) connect(Cortex[L5A][column][Glu], Cortex[L5A][column][GABA], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L5A_to_L5A) #connect(Cortex[L5A][column][Glu], Cortex[L5B][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5A_to_L5B) connect(Cortex[L5A][column][Glu], Cortex[L6][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5A_to_L6) # for GABA connect(Cortex[L5A][column][GABA], Cortex[L5A][column][Glu], neurotransmitter=GABA, weight_coef=1.5) ''' L5B ''' # for Glu connect(Cortex[L5B][column][Glu], Cortex[L2][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5B_to_L2) connect(Cortex[L5B][column][Glu], Cortex[L3][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5B_to_L3) connect(Cortex[L5B][column][Glu], Cortex[L4][column][Glu], neurotransmitter=Glu, weight_coef=0.8, conn_prob=L5B_to_L4) connect(Cortex[L5B][column][Glu], Cortex[L5B][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L5B_to_L5B) connect(Cortex[L5B][column][Glu], Cortex[L5B][column][GABA], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L5B_to_L5B) #connect(Cortex[L5B][column][Glu], Cortex[L6][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L5B_to_L6) # for GABA connect(Cortex[L5B][column][GABA], Cortex[L5B][column][Glu], neurotransmitter=GABA, weight_coef=1.5) ''' L6 ''' # for Glu connect(Cortex[L6][column][Glu], Cortex[L4][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L6_to_L4) connect(Cortex[L6][column][Glu], Cortex[L5A][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L6_to_L5A) connect(Cortex[L6][column][Glu], Cortex[L5B][column][Glu], neurotransmitter=Glu, weight_coef=1.0, conn_prob=L6_to_L5B) connect(Cortex[L6][column][Glu], Cortex[L6][column][Glu], neurotransmitter=Glu, weight_coef=0.7, conn_prob=L6_to_L6) connect(Cortex[L6][column][Glu], Cortex[L6][column][GABA], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L6_to_L6) # for GABA connect(Cortex[L6][column][GABA], Cortex[L4][column][Glu], neurotransmitter=GABA, weight_coef=1.5) connect(Cortex[L6][column][GABA], Cortex[L6][column][Glu], neurotransmitter=GABA, weight_coef=1.5) logger.debug("* * * Adding neighbors connections") for column in range(column_number): for neighbor in neighbors[column]: # L2 layer connect(Cortex[L2][column][Glu], Cortex[L2][neighbor][Glu], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L2_to_L2) # L3 layer #connect(Cortex[L3][column][Glu], Cortex[L3][neighbor][Glu], syn_type=Glu, weight_coef=1.0, conn_prob=L3_to_L3) # L5A layer connect(Cortex[L5A][column][Glu], Cortex[L5A][neighbor][Glu], neurotransmitter=Glu, weight_coef=0.5, conn_prob=L5A_to_L5A) logger.debug("* * * Connect generators") specific_generator(Cortex[L6][2][Glu], coef_part=0.3) logger.debug("* * * Connect detectors") set_flag_to_column(2, neurotransmitter=both, heatmap=True, multimeter=True) set_flag_to_layer(L5A, neurotransmitter=both, heatmap=True, multimeter=False) logger.debug("* * * Add wafe") big_wave(rate_HZ=20, percent=100) g.endbuild = datetime.datetime.now() simulate() log() save()
{ "repo_name": "research-team/robot-dream", "path": "somatosensory_columns/main.py", "copies": "1", "size": "6462", "license": "mit", "hash": 8536796009368931000, "line_mean": 62.9900990099, "line_max": 130, "alpha_frac": 0.6928195605, "autogenerated": false, "ratio": 2.3644346871569706, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.355725424765697, "avg_score": null, "num_lines": null }
from functions import * print "Attempting to read cached updates data." try: file = open("sample_times,samples,period,modes,updates.pickle", "rb") sample_times, samples, period, modes, updates = UnpickleThis("sample_times,samples,period,modes,updates.pickle") print "Read in cached updates data. There are {0} updates.".format(len(updates)) except: print "No cached updates data. Starting fresh from dynamics data." # sample_times is a list of scalars, samples is a list of 3-vectors, and period is a positive scalar. # The Heisenberg dynamics as defined by the data in this file is defined as follows. The elements # in samples and sample_times (of which there should be an identical number) pair up to form pairs # of the form (sample_times[0],samples[0]), (sample_times[1],samples[1]), ..., which define a # discrete sampling (t,p(t)) of the path function p : [0,period] -> R^3. print "Attempting to read dynamics data." sample_times, samples, period = UnpickleThis("../initial-conditions-dynamics/sample_times,samples,period.pickle") # Turn the list of 3-vector samples into a list of complex 3-vectors so that we can pipe it through # the Fourier code more readily. samples = [ComplexVector(*sample) for sample in samples] print "period = {0}, len(sample_times) = {1}, len(samples) = {2}".format(period, len(sample_times), len(samples)) # L is the number (on each side of 0) of coefficients to use in the Fourier sum. L = 60 # modes is the list of modes (cycle counts based on the period) to use in Fourier operations. # We can have this be a sparser list, for example [-9, -6, -3, 0, 3, 6, 9], in which case, # the missing modes are assumed to have Fourier coefficient 0. modes = [k for k in range(-L,L+1)] # modes = [k for k in range(-L,L+1) if Modulo(k,3) == 1] # Compute the Fourier coefficients of the Heisenberg dynamics that was read in from the file. print "Computing the Fourier coefficients of the dynamics." coefficients = FourierExpansion(sample_times, samples, period, modes) # Verify that the energy of the Fourier sum expression of the dynamics is equal to 0 (up to numerical error). derivative_coefficients = FourierDerivative(modes, coefficients, period) position_samples = [FourierSum(modes, coefficients, period, t) for t in sample_times] derivative_samples = [FourierSum(modes, derivative_coefficients, period, t) for t in sample_times] energy_samples = [Energy(position_sample, derivative_sample) \ for (position_sample,derivative_sample) in izip(position_samples,derivative_samples)] print "energy_samples:" PrintNiceList(energy_samples) # Initialize the updates list with the initial set of Fourier coefficients. updates = [coefficients] # This Sage pane runs step_count iterations of the [gradient descent] Update function. # The higher step_count is, the longer it will take (the time will increase linearly # with step_count). Note that RunUpdates stores its computations in the updates list, # and if you run RunUpdates again, it will continue where it left off. Thus in theory # it should be possible to interrupt (Esc key) the process and then continue it later # without losing data. step_count = 100 step_size = 0.1 print "Computing {0} gradient descent updates.".format(step_count) RunUpdates(modes, period, updates, step_count, step_size) print "There are now {0} updates computed. Caching this data to file.".format(len(updates)) data = [sample_times, samples, period, modes, updates] PickleThis(data, "sample_times,samples,period,modes,updates.pickle") # This reconstructs the paths from the Fourier coefficients in updates, and stores them in a file. print "Reconstructing the dynamics from its Fourier coefficients (for each update)." sparser_sample_times = [t for t in linterp(0.0, 273.5, value_count=400)] # reconstructed_samples = [[FourierSum(modes, coefficients, period, t) for t in sparser_sample_times] for coefficients in updates] reconstructed_samples = [] for (i,coefficients) in enumerate(updates): print "Reconstructing dynamics for update {0}.".format(i) reconstructed_samples.append([FourierSum(modes, coefficients, period, t) for t in sparser_sample_times]) print "Storing reconstructed dynamics to file." PickleThis(reconstructed_samples, "reconstructed_samples.pickle")
{ "repo_name": "vdods/heisenberg", "path": "attic/fourier-analysis/main.py", "copies": "1", "size": "4299", "license": "mit", "hash": -21598899352828812, "line_mean": 59.5492957746, "line_max": 130, "alpha_frac": 0.7506396836, "autogenerated": false, "ratio": 3.526661197703035, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4777300881303035, "avg_score": null, "num_lines": null }
from Functions import * while True: option = input('(L)ab 1, (T)aller 2: ') if option == 'L': num = input('Numeral: ') if num == '1': func = 'np.exp(x) - 3*x' x0 = input('Ingrese límite inferior: ') x1 = input('Ingrese límite superior: ') par = input('¿Realizar 6 iteraciones? (S/N): ') if par == 'S': par = True else: par = False bolzano(func, float(x0), float(x1), par, 0.0001) elif num == '3': func = 'x**3 + x - 6' x0 = input('Ingrese límite inferior: ') x1 = input('Ingrese límite superior: ') mode = input('Algoritmo (1=Bolzano, 2=Pos. Falsa): ') if mode == '1': bolzano(func, float(x0), float(x1), False, 0.001) elif mode == '2': regula(func, float(x0), float(x1), 0.001) elif num == '5': func = '(4*x - 7) / (x - 2)' dfunc = '(-1) / ((x - 2)**2)' x0 = input('Ingrese punto de inicio: ') nwtn(func,dfunc,float(x0),0.0001) elif num == '7': func = 'np.sin(x) + np.cos(x) - 1.1' dfunc = 'np.cos(x) - np.sin(x)' x0 = input('Ingrese límite inferior: ') x1 = input('Ingrese límite superior: ') mode = input('Algoritmo (1=Bolzano, 2=Pos. Falsa, 3=Newton, 4=Secante): ') if mode == '1': bolzano(func, float(x0), float(x1), False, 0.0001) elif mode == '2': regula(func, float(x0), float(x1), 0.0001) elif mode == '3': nwtn(func, dfunc, (float(x0)+float(x1))/2, 0.0001) elif mode == '4': secante(func, float(x0), float(x1), 0.0001) elif option == 'T': check = False print('Interpolación por Método de Lagrange') while (check == False): xi = input('Datos X (separados por espacios): ') yi = input('Datos Y (separados por espacios): ') X = [float(i) for i in xi.split()] Y = [float(j) for j in yi.split()] if (len(X) == len(Y)): check = True else: print("\t#X ≠ #Y, intente de nuevo.") lagrange(X,Y)
{ "repo_name": "queq/just-stuff", "path": "python/lab-1/main.py", "copies": "1", "size": "1839", "license": "mit", "hash": -267747093116807360, "line_mean": 31.0701754386, "line_max": 77, "alpha_frac": 0.5705689278, "autogenerated": false, "ratio": 2.3316326530612246, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3402201580861225, "avg_score": null, "num_lines": null }
from functions import prime_sieve, primefactors import time import math times = [] times += [time.clock()] limit = 1000000 primes = prime_sieve(int(math.sqrt(limit))) maximum = 2 maxn = 2 # phi(2n) = {2phi(n) if n is even; phi(n) if odd} # phi(nm) = phi(n) * phi(m) if n, m are coprime # maxn will be even but eventually need to calculate some odd values # searching the range by calculating totients takes about a minute... # totients = {2:1} # for n in range(3, limit): # if not n % 2: # m = n // 2 # value = totients[m] # if not m % 2: # value *= 2 # else: # value = totient(n, primes) # totients[n] = value # x = n / value # if x > maximum: # maximum = x # maxn = n # ... but is a waste of time. some alegbra reveals: # n/phi(n) = pi(p/(p-1)) for p|n # which is maximized by pi(p) for p < n value = 1 maxp = 2 for p in primes: value *= p if value > limit: value = value // p break maxp = p if value == limit: break print(value) times += [time.clock()] print(times[-1] - times[-2])
{ "repo_name": "esosn/euler", "path": "69.py", "copies": "1", "size": "1111", "license": "mit", "hash": 8294753654031220000, "line_mean": 21.693877551, "line_max": 69, "alpha_frac": 0.5661566157, "autogenerated": false, "ratio": 2.8055555555555554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8864143209604962, "avg_score": 0.0015137923301188608, "num_lines": 49 }
from functions import * from time import sleep def run_calculator(): """ A Simple Calculator """ list_choices = ['Addition: 1', 'Subtraction: 2', 'Multiplication: 3', 'Division: 4', 'Exponent: 5', 'Logarithm: 6', 'Square Root: 7', 'Cube Root: 8', 'Sin: 9', 'Cos: 10', 'Tan: 11'] print('============================') for item in list_choices: print(item) print('============================') user_choice = input('Enter number of selection: ') if user_choice == '1': addition() elif user_choice == '2': subtraction() elif user_choice == '3': multiplication() elif user_choice == '4': division() elif user_choice == '5': exponent() elif user_choice == '6': logarithm() elif user_choice == '7': square_root() elif user_choice == '8': cube_root() elif user_choice == '9': sin_a() elif user_choice == '10': cos_a() elif user_choice == '11': tan_a() else: print('Invalid Selection...') sleep(2) run_calculator() run_calculator()
{ "repo_name": "Apsis/Synthetic-Programming", "path": "Simple Calculator/main.py", "copies": "1", "size": "1381", "license": "mit", "hash": -9109832418679094000, "line_mean": 22.2280701754, "line_max": 54, "alpha_frac": 0.4098479363, "autogenerated": false, "ratio": 4.398089171974522, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009746588693957114, "num_lines": 57 }
from ..functions import sqrt from .rv import (cdf, density, dependent, expectation, given, independent, probability, pspace, random_symbols, sample, sample_iter, sampling_density, where) __all__ = ('P', 'E', 'density', 'where', 'given', 'sample', 'cdf', 'pspace', 'sample_iter', 'variance', 'std', 'skewness', 'covariance', 'dependent', 'independent', 'random_symbols', 'correlation', 'moment', 'cmoment', 'sampling_density') def moment(X, n, c=0, condition=None, **kwargs): """ Return the nth moment of a random expression about c i.e. E((X-c)**n) Default value of c is 0. Examples ======== >>> from diofant.stats import Die, E >>> X = Die('X', 6) >>> moment(X, 1, 6) -5/2 >>> moment(X, 2) 91/6 >>> moment(X, 1) == E(X) True """ return expectation((X - c)**n, condition, **kwargs) def variance(X, condition=None, **kwargs): """ Variance of a random expression Expectation of (X-E(X))**2 Examples ======== >>> from diofant.stats import Die, Bernoulli >>> X = Die('X', 6) >>> p = Symbol('p') >>> B = Bernoulli('B', p, 1, 0) >>> variance(2*X) 35/3 >>> simplify(variance(B)) p*(-p + 1) """ return cmoment(X, 2, condition, **kwargs) def standard_deviation(X, condition=None, **kwargs): """ Standard Deviation of a random expression Square root of the Expectation of (X-E(X))**2 Examples ======== >>> from diofant.stats import Bernoulli >>> p = Symbol('p') >>> B = Bernoulli('B', p, 1, 0) >>> simplify(std(B)) sqrt(p*(-p + 1)) """ return sqrt(variance(X, condition, **kwargs)) std = standard_deviation def covariance(X, Y, condition=None, **kwargs): """ Covariance of two random expressions The expectation that the two variables will rise and fall together Covariance(X,Y) = E( (X-E(X)) * (Y-E(Y)) ) Examples ======== >>> from diofant.stats import Exponential >>> rate = Symbol('lambda', positive=True, real=True) >>> X = Exponential('X', rate) >>> Y = Exponential('Y', rate) >>> covariance(X, X) lambda**(-2) >>> covariance(X, Y) 0 >>> covariance(X, Y + rate*X) 1/lambda """ return expectation( (X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs)), condition, **kwargs) def correlation(X, Y, condition=None, **kwargs): """ Correlation of two random expressions, also known as correlation coefficient or Pearson's correlation The normalized expectation that the two variables will rise and fall together Correlation(X,Y) = E( (X-E(X)) * (Y-E(Y)) / (sigma(X) * sigma(Y)) ) Examples ======== >>> from diofant.stats import Exponential >>> rate = Symbol('lambda', positive=True, real=True) >>> X = Exponential('X', rate) >>> Y = Exponential('Y', rate) >>> correlation(X, X) 1 >>> correlation(X, Y) 0 >>> correlation(X, Y + rate*X) 1/sqrt(1 + lambda**(-2)) """ return covariance(X, Y, condition, **kwargs)/(std(X, condition, **kwargs) * std(Y, condition, **kwargs)) def cmoment(X, n, condition=None, **kwargs): """ Return the nth central moment of a random expression about its mean i.e. E((X - E(X))**n) Examples ======== >>> from diofant.stats import Die >>> X = Die('X', 6) >>> cmoment(X, 3) 0 >>> cmoment(X, 2) 35/12 >>> cmoment(X, 2) == variance(X) True """ mu = expectation(X, condition, **kwargs) return moment(X, n, mu, condition, **kwargs) def smoment(X, n, condition=None, **kwargs): """ Return the nth Standardized moment of a random expression i.e. E( ((X - mu)/sigma(X))**n ) Examples ======== >>> from diofant.stats import Exponential >>> rate = Symbol('lambda', positive=True, real=True) >>> Y = Exponential('Y', rate) >>> smoment(Y, 4) 9 >>> smoment(Y, 4) == smoment(3*Y, 4) True >>> smoment(Y, 3) == skewness(Y) True """ sigma = std(X, condition, **kwargs) return (1/sigma)**n*cmoment(X, n, condition, **kwargs) def skewness(X, condition=None, **kwargs): """ Measure of the asymmetry of the probability distribution Positive skew indicates that most of the values lie to the right of the mean skewness(X) = E( ((X - E(X))/sigma)**3 ) Examples ======== >>> from diofant.stats import Exponential, Normal >>> X = Normal('X', 0, 1) >>> skewness(X) 0 >>> rate = Symbol('lambda', positive=True, real=True) >>> Y = Exponential('Y', rate) >>> skewness(Y) 2 """ return smoment(X, 3, condition, **kwargs) P = probability E = expectation
{ "repo_name": "diofant/diofant", "path": "diofant/stats/rv_interface.py", "copies": "2", "size": "4892", "license": "bsd-3-clause", "hash": -1353850904711446300, "line_mean": 21.6481481481, "line_max": 80, "alpha_frac": 0.5515126738, "autogenerated": false, "ratio": 3.440225035161744, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49917377089617443, "avg_score": null, "num_lines": null }
from .functions import Textile class TextileFactory(object): """ Use TextileFactory to create a Textile object which can be re-used to process multiple strings with the same settings. >>> f = TextileFactory() >>> f.process("some text here") '\\t<p>some text here</p>' >>> f = TextileFactory(restricted=True) >>> f.process("more text here") '\\t<p>more text here</p>' Certain parameter values are not permitted because they are illogical: >>> f = TextileFactory(lite=True) Traceback (most recent call last): ... ValueError: lite can only be enabled in restricted mode >>> f = TextileFactory(head_offset=7) Traceback (most recent call last): ... ValueError: head_offset must be 0-6 >>> f = TextileFactory(html_type='html5') Traceback (most recent call last): ... ValueError: html_type must be 'html' or 'xhtml' """ def __init__(self, restricted=False, lite=False, sanitize=False, noimage=None, auto_link=False, get_sizes=False, head_offset=0, html_type='xhtml'): self.class_parms = {} self.method_parms = {} if lite and not restricted: raise ValueError("lite can only be enabled in restricted mode") if restricted: self.class_parms['restricted'] = True self.class_parms['lite'] = lite self.method_parms['rel'] = 'nofollow' if noimage is None: if restricted: noimage = True else: noimage = False self.class_parms['noimage'] = noimage self.method_parms['sanitize'] = sanitize self.class_parms['auto_link'] = auto_link self.class_parms['get_sizes'] = get_sizes if int(head_offset) not in list(range(0, 6)): raise ValueError("head_offset must be 0-6") else: self.method_parms['head_offset'] = head_offset if html_type not in ['html', 'xhtml']: raise ValueError("html_type must be 'html' or 'xhtml'") else: self.method_parms['html_type'] = html_type def process(self, text): return Textile(**self.class_parms).textile(text, **self.method_parms)
{ "repo_name": "timonwong/OmniMarkupPreviewer", "path": "OmniMarkupLib/Renderers/libs/python3/textile/textilefactory.py", "copies": "2", "size": "2255", "license": "mit", "hash": -7274836619988116000, "line_mean": 29.472972973, "line_max": 77, "alpha_frac": 0.5920177384, "autogenerated": false, "ratio": 3.9770723104056436, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 74 }
from functions import Textile class TextileFactory(object): """ Use TextileFactory to create a Textile object which can be re-used to process multiple strings with the same settings. >>> f = TextileFactory() >>> f.process("some text here") '\\t<p>some text here</p>' >>> f = TextileFactory(restricted=True) >>> f.process("more text here") '\\t<p>more text here</p>' Certain parameter values are not permitted because they are illogical: >>> f = TextileFactory(lite=True) Traceback (most recent call last): ... ValueError: lite can only be enabled in restricted mode >>> f = TextileFactory(head_offset=7) Traceback (most recent call last): ... ValueError: head_offset must be 0-6 >>> f = TextileFactory(html_type='html5') Traceback (most recent call last): ... ValueError: html_type must be 'html' or 'xhtml' """ def __init__(self, restricted=False, lite=False, sanitize=False, noimage=None, auto_link=False, get_sizes=False, head_offset=0, html_type='xhtml'): self.class_parms = {} self.method_parms = {} if lite and not restricted: raise ValueError("lite can only be enabled in restricted mode") if restricted: self.class_parms['restricted'] = True self.class_parms['lite'] = lite self.method_parms['rel'] = 'nofollow' if noimage is None: if restricted: noimage = True else: noimage = False self.class_parms['noimage'] = noimage self.method_parms['sanitize'] = sanitize self.class_parms['auto_link'] = auto_link self.class_parms['get_sizes'] = get_sizes if int(head_offset) not in range(0, 6): raise ValueError("head_offset must be 0-6") else: self.method_parms['head_offset'] = head_offset if html_type not in ['html', 'xhtml']: raise ValueError("html_type must be 'html' or 'xhtml'") else: self.method_parms['html_type'] = html_type def process(self, text): return Textile(**self.class_parms).textile(text, **self.method_parms)
{ "repo_name": "Lyleo/OmniMarkupPreviewer", "path": "OmniMarkupLib/Renderers/libs/python2/textile/textilefactory.py", "copies": "2", "size": "2248", "license": "mit", "hash": -8898333770990043000, "line_mean": 29.3783783784, "line_max": 77, "alpha_frac": 0.5920818505, "autogenerated": false, "ratio": 3.9858156028368796, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 74 }
from .functions import vtos, stov class ModelFile: def __init__(self, filename, mode='r'): self.__fp = open(filename, mode) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.__fp.close() return False def write(self, x): print(x, file=self.__fp) def __write_vector(self, x): self.write(vtos(x)) def __write_matrix(self, x): for row in x: self.__write_vector(row) def read(self): return next(self.__fp).strip() def __read_vector(self, x, tp): data = stov(self.read(), tp) for i in range(len(data)): x[i] = data[i] def __read_matrix(self, x, tp): for row in x: self.__read_vector(row, tp) def write_embed(self, f): self.__write_matrix(f.W) def write_linear(self, f): self.__write_matrix(f.W) self.__write_vector(f.b) def read_embed(self, f): self.__read_matrix(f.W, float) def read_linear(self, f): self.__read_matrix(f.W, float) self.__read_vector(f.b, float) def get_file_pointer(self): return self.__fp
{ "repo_name": "odashi/chainer_examples", "path": "chainer-1.4/util/model_file.py", "copies": "1", "size": "1198", "license": "mit", "hash": 4992737684497897000, "line_mean": 22.0384615385, "line_max": 55, "alpha_frac": 0.530884808, "autogenerated": false, "ratio": 3.3185595567867034, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4349444364786703, "avg_score": null, "num_lines": null }
from ..functions.messages import SaveDraftRequest from ..types import UpdateDraftMessage class Draft: """ Custom class that encapsulates a draft on the Telegram servers, providing an abstraction to change the message conveniently. The library will return instances of this class when calling `client.get_drafts()`. """ def __init__(self, client, peer, draft): self._client = client self._peer = peer self.text = draft.message self.date = draft.date self.no_webpage = draft.no_webpage self.reply_to_msg_id = draft.reply_to_msg_id self.entities = draft.entities @classmethod def _from_update(cls, client, update): if not isinstance(update, UpdateDraftMessage): raise ValueError( 'You can only create a new `Draft` from a corresponding ' '`UpdateDraftMessage` object.' ) return cls(client=client, peer=update.peer, draft=update.draft) @property def entity(self): return self._client.get_entity(self._peer) @property def input_entity(self): return self._client.get_input_entity(self._peer) def set_message(self, text, no_webpage=None, reply_to_msg_id=None, entities=None): """ Changes the draft message on the Telegram servers. The changes are reflected in this object. Changing only individual attributes like for example the `reply_to_msg_id` should be done by providing the current values of this object, like so: draft.set_message( draft.text, no_webpage=draft.no_webpage, reply_to_msg_id=NEW_VALUE, entities=draft.entities ) :param str text: New text of the draft :param bool no_webpage: Whether to attach a web page preview :param int reply_to_msg_id: Message id to reply to :param list entities: A list of formatting entities :return bool: `True` on success """ result = self._client(SaveDraftRequest( peer=self._peer, message=text, no_webpage=no_webpage, reply_to_msg_id=reply_to_msg_id, entities=entities )) if result: self.text = text self.no_webpage = no_webpage self.reply_to_msg_id = reply_to_msg_id self.entities = entities return result def delete(self): """ Deletes this draft :return bool: `True` on success """ return self.set_message(text='')
{ "repo_name": "andr-04/Telethon", "path": "telethon/tl/custom/draft.py", "copies": "1", "size": "2627", "license": "mit", "hash": -2115114454082083300, "line_mean": 31.8375, "line_max": 86, "alpha_frac": 0.6003045299, "autogenerated": false, "ratio": 4.299509001636661, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00014367816091954023, "num_lines": 80 }
from functions_text import * from roulette_player import * ###### PLAYER TURN ###### def turn(active, bets, betsMoney, betsType, money, name, gender, simpleChances): betMade = False input("{0}, tapez Entrée pour faire vos jeux.".format(name[active])) while not(betMade): ### PRINT MENU AND GET INPUT ### choices = [1, 2, 3, 4, 5, 6, 7, 8] titleL("MENU PERSONNEL") print("{0}, vous avez {1} dollar{2}. Vous pouvez :".format(name[active], money[active], plural(money[active]))) print("(1.) Miser sur un plein") print("(2.) Miser sur un cheval") print("(3.) Miser sur une transversale") print("(4.) Miser sur un carré") print("(5.) Miser sur un sixain") print("(6.) Miser sur une colonne") print("(7.) Miser sur deux colonnes") print("(8.) Miser sur une chance simple") choice = getIntList(0, choices, "Que faites-vous ?") endL(False) if choice == 1: bets, betsMoney, betsType, betMade, money = plein(active, bets, betsMoney, betsType, money, betMade) elif choice == 2: bets, betsMoney, betsType, betMade, money = cheval(active, bets, betsMoney, betsType, money, betMade) elif choice == 3: bets, betsMoney, betsType, betMade, money = transv(active, bets, betsMoney, betsType, money, betMade) elif choice == 4: bets, betsMoney, betsType, betMade, money = carre(active, bets, betsMoney, betsType, money, betMade) elif choice == 5: bets, betsMoney, betsType, betMade, money = sixain(active, bets, betsMoney, betsType, money, betMade) elif choice == 6: bets, betsMoney, betsType, betMade, money = colonne(active, bets, betsMoney, betsType, money, betMade) elif choice == 7: bets, betsMoney, betsType, betMade, money = dcolonnes(active, bets, betsMoney, betsType, money, betMade) elif choice == 8: bets, betsMoney, betsType, betMade, money = simple(active, bets, betsMoney, betsType, money, betMade, simpleChances)
{ "repo_name": "cpvannier/western", "path": "roulette_turn.py", "copies": "1", "size": "2139", "license": "apache-2.0", "hash": -1153894462859193300, "line_mean": 44.4680851064, "line_max": 128, "alpha_frac": 0.6036499766, "autogenerated": false, "ratio": 3.133431085043988, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4237081061643988, "avg_score": null, "num_lines": null }
from functions_text import * from western_player import * ###### PLAYER TURN ###### def turn(active, players, rooms, room, actions, bullets, defense, life, alive, killer, traitors, traitor, detective, gender, name, title, sniper, playerTNT, roomTNT, playerBlock, roomBlock, roomBlocked): actionsTemp = actions[active] input("{0}, tapez Entrée pour commencer votre tour.".format(name[active])) while actionsTemp > 0: ### PRINT MENU AND GET INPUT ### choices = [1, 2, 4, 5, 6] titleL("MENU PERSONNEL") print("{0}, vous êtes un{1} {2}!".format(name[active], gender[active], title[active]), end = " ") print("Vous vous trouvez dans la salle {0}, avec {1} point{2} de vie et {3} balle{4}.".format(room[active] + 1, life[active], plural(life[active]), bullets[active], plural(bullets[active]))) print("Il vous reste {0} point{1} d'action. Vous pouvez :".format(actionsTemp, plural(actionsTemp))) print("(1.) Voir le tableau récapitulatif (n'utilise pas de points d'actions)") print("(2.) Vous déplacer") if bullets[active] > 0 and alive.count(True) >= 2: print("(3.) Tirer ({0} balle{1} dans votre arme)".format(bullets[active], plural(bullets[active]))) choices.append(3) print("(4.) Fouiller la salle") print("(5.) Vous défendre (contre un tir)") print("(6.) Quitter") if sniper[active] > 0 and alive.count(True) >= 2: print("(7.) Tirer au Sniper ({0} balle{1} dans votre arme)".format(sniper[active], plural(sniper[active]))) choices.append(7) if playerTNT[active] > 0: print("(8.) Utiliser de la TNT dans la salle {0} ({1} pain{2} de dynamite disponible)".format(room[active] + 1, playerTNT[active], plural(playerTNT[active]))) choices.append(8) if playerBlock[active] > 0: print("(9.) Barricader la salle {0} (vous pouvez faire {1} barricade{2})".format(room[active] + 1, playerBlock[active], plural(playerBlock[active]))) choices.append(9) if detective[active] and alive.count(True) < players: print("(10.) Faire une autopsie sur un mort") choices.append(10) choice = getIntList(0, choices, "Que faites-vous ?") endL(False) ### ACTIVATE THE FUNCTIONS ### if choice == 1: recap(active, players, name, title, traitor, life, alive, room) elif choice == 2: move(active, rooms, room, roomBlocked) actionsTemp -= 1 elif choice == 3: shoot(active, players, room, life, alive, killer, bullets, name, defense) actionsTemp -= 1 elif choice == 4: seek(active, room, sniper, playerTNT, playerBlock) actionsTemp -= 1 elif choice == 5: titleL("DEFENSE*") defense[active] += 1 print("Vous êtes prêts à esquiver la prochaîne attaque.") endL(True) actionsTemp -= 1 elif choice == 6: break elif choice == 7: snipe(active, players, room, life, alive, killer, sniper, name, defense) actionsTemp -=1 elif choice == 8: explode(active, room, playerTNT, roomTNT) actionsTemp -= 1 elif choice == 9: titleL("BARRICADER") roomBlock[room[active]] = True playerBlock[active] -= 1 if playerBlock[active] < 0: playerBlock[active] = 0 print("Vous avez barricadé la salle {0} pour le prochain tour.".format(room[active] + 1)) actionsTemp -= 1 elif choice == 10: autopsy(active, players, alive, room, name, title, gender, killer) actionsTemp -= 1 else: print("WTF?!")
{ "repo_name": "cpvannier/western", "path": "western_turn.py", "copies": "1", "size": "3872", "license": "apache-2.0", "hash": 4502938962606807000, "line_mean": 46.0975609756, "line_max": 203, "alpha_frac": 0.5735370274, "autogenerated": false, "ratio": 3.369982547993019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4443519575393019, "avg_score": null, "num_lines": null }
from ...functions.xml.deff import * def nextquantity(s,l,t): return wrap("next", t[2]) def damage(s,l,t): return wrap("damage", t[0]) def combatdamage(s,l,t): combat = emptytag("combat") return wrap("damage", [combat,t[1]]) def noncombatdamage(s,l,t): noncombat = emptytag("noncombat") return wrap("damage", [noncombat,t[1]]) def thisturn(s,l,t): return wrap("turn", emptytag("this")) def where(s,l,t): return wrap("defx", wrap("number", t[0])) def equal(s,l,t): return wrap("equal", wrap("number", t[0])) def for_(s,l,t): return wrap("for", t[1]) def destroy(s,l,t): return wrap("destroy", t[1]) def cantregenerate(s,l,t): return wrap("cant", emptytag("regenerate")) def exile(s,l,t): if 4 == len(t): fromwhere = t[3] details = [t[1], fromwhere] else: details = t[1] return wrap("exile", details) def scry(s,l,t): return wrap("scry", t[1]) def gainlife(s,l,t): return wrap("gain", wrap("life", t[1])) def tap(s,l,t): return wrap("tap", t[1]) def untap(s,l,t): return wrap("untap", t[1]) def draw(s,l,t): return wrap("draw", t[1]) def discard(s,l,t): if 3 == len(t): atrandom = emptytag("random") what = [atrandom, t[1]] else: what = t[1] return wrap("discard", what) def loselife(s,l,t): return wrap("lose", wrap("life", t[1])) def dealquantitydamage(s,l,t): details = [t[1], t[4]] return wrap("deal", details) def dealdamage(s,l,t): return wrap("deal", t[3]) def sacrifice(s,l,t): return wrap("sacrifice", t[1]) def regenerate(s,l,t): return wrap("regenerate", t[1]) def putcounter(s,l,t): counter = wrap("counter", t[1:2]) obj = t[5] return wrap("put", [counter, obj]) def tokens(s,l,t): return wrap("token", t) def puttoken(s,l,t): return wrap("puttoken", t) def return_(s,l,t): return wrap("return", t) def become(s,l,t): return wrap("become", t[1]) def bereduced(s,l,t): return wrap("decreaseby", t[3]) def paylife(s,l,t): return wrap("pay", wrap("life", t[1])) def prevention(s,l,t): return wrap("prevention", t) def addmana(s,l,t): who = wrap("who", t[4]) howmuch = t[1] return wrap("addmana", [howmuch, who]) def counterspell(s,l,t): return wrap("counterspell", t[1]) def effect(s,l,t): if 2 == len(t): details = t[0:1] else: details = t[0] return wrap("effect", details) def oneshot(s,l,t): return wrap("oneshot", t)
{ "repo_name": "jrgdiz/cardwalker", "path": "grammar/rules/oneshot/act.py", "copies": "1", "size": "2324", "license": "mit", "hash": -361483554068445300, "line_mean": 17.75, "line_max": 44, "alpha_frac": 0.6256454389, "autogenerated": false, "ratio": 2.26953125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8027224807260157, "avg_score": 0.07359037632796857, "num_lines": 124 }
from .function_type import FunctionType, Invokable, IntrinsicCallable from .containers import Temporary class MacroType(FunctionType, Invokable): def __init__(self, ret_type, params, body, typescope, compiletime): super().__init__(ret_type, params, True, False) self._typescope = typescope if type(body) == tuple: self._body, self._init_list = body else: self._body, self._init_list = body, False self.compiletime = compiletime def allocate(self, compiler, namehint): func = super().allocate(compiler, namehint) func.set_as_intrinsic(IntrinsicCallable(self.__expand)) return func def __expand(self, compiler, container, args): if self.compiletime: return self.__expand_compiletime(compiler, args) else: return self.__expand_macro(compiler, args) def __expand_macro(self, compiler, args, ret_does_return=False): with compiler._process_body_main(self.ret_type, return_var=False, ret_does_return=ret_does_return) as ret: with compiler.types.typescope(self._typescope): compiler._alloc_and_copy_params(self.params, args) if self._init_list != False: compiler.construct_this(self._init_list) compiler.transform(self._body) if ret is None: return Temporary(compiler.type('void'), None) return ret def __expand_compiletime(self, compiler, args): with compiler.compiletime(): return self.__expand_macro(compiler, args, True)
{ "repo_name": "simon816/Command-Block-Assembly", "path": "cbl/macro_type.py", "copies": "1", "size": "1647", "license": "mit", "hash": -3545487537936638000, "line_mean": 40.175, "line_max": 74, "alpha_frac": 0.6114146934, "autogenerated": false, "ratio": 4.12781954887218, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.523923424227218, "avg_score": null, "num_lines": null }
from functools import cached_property from typing import Dict, Iterable, Optional, Protocol, Type, TypeVar, Union import requests from django.conf import settings from django.contrib import messages from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.models import AnonymousUser from django.core.handlers.wsgi import WSGIRequest from django.db.models import Model, QuerySet from django.http.response import HttpResponseForbidden, HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect from django.urls import reverse from guardian.mixins import LoginRequiredMixin from accounts.backends import TWO_FACTOR_AUTH_SESSION_KEY from accounts.models import User from studies.models import Lab, Response, Study, StudyType from studies.permissions import StudyPermission LookitUser = Union[User, AnonymousUser] LookitObject = Union[Lab, Study, Response] ModelType = TypeVar("ModelType", bound=Model) class LookitRequest(WSGIRequest): """Custom stub to help recognize custom AUTH_USER_MODEL. See: https://github.com/typeddjango/django-stubs#how-can-i-create-a-httprequest-thats-guaranteed-to-have-an-authenticated-user """ user: LookitUser class LookitHandlerBase: request: LookitRequest args: Iterable kwargs: Dict class ResearcherLoginRequiredMixin(LookitHandlerBase, LoginRequiredMixin): """Require logged-in user; if not logged in, redirect to researcher login.""" def dispatch(self, request, *args, **kwargs): """Dispatch override.""" user = request.user # Potential anonymous user should not break the view. is_researcher = getattr(user, "is_researcher", False) two_factor_auth_enabled = request.session.get(TWO_FACTOR_AUTH_SESSION_KEY) if is_researcher: if two_factor_auth_enabled: return super().dispatch(request, *args, **kwargs) else: messages.error( request, "In order to access researcher pages, you must have two-factor " "authentication enabled, and have logged in with your OTP key.", ) return redirect("accounts:2fa-login") else: if user.is_authenticated: return HttpResponseForbidden( f"Researcher account required to see Experimenter app." ) else: messages.info( request, "Please sign in with your researcher account to see Experimenter app.", ) return HttpResponseRedirect(reverse("login")) class StudyLookupMixin(LookitHandlerBase): @cached_property def study(self): return get_object_or_404(Study, pk=self.kwargs.get("pk")) class CanViewStudyResponsesMixin( ResearcherLoginRequiredMixin, UserPassesTestMixin, StudyLookupMixin ): raise_exception = True def can_view_responses(self): user = self.request.user study = self.study return user.is_researcher and ( user.has_study_perms(StudyPermission.READ_STUDY_RESPONSE_DATA, study) or user.has_study_perms(StudyPermission.READ_STUDY_PREVIEW_DATA, study) ) test_func = can_view_responses class SingleObjectFetchProtocol(Protocol[ModelType]): model: Type[ModelType] object: ModelType def get_object(self, queryset: Optional[QuerySet] = None) -> ModelType: """Override get_object() to be smarter. This is to allow us to get the study for use the predicate function of UserPassesTestMixin without making `SingleObjectMixin.get` (called within the context of `View.dispatch`) issue a second expensive query. """ if getattr(self, "object", None) is None: # Only call get_object() when self.object isn't present. self.object: ModelType = super().get_object(queryset) return self.object class StudyTypeMixin: request: LookitRequest def validate_and_fetch_metadata(self, study_type: Optional[StudyType] = None): """Gets the study type and runs hardcoded validations. TODO: this is obviously a fragile pattern, and there's probably a better way to do this. Let's think of a way to do this more dynamically in the future. :return: A tuple of boolean and tuple, the inner tuple containing error data. """ if not study_type: target_study_type_id = self.request.POST["study_type"] study_type = StudyType.objects.get(id=target_study_type_id) metadata = self.extract_type_metadata(study_type=study_type) errors = VALIDATIONS.get(study_type.name, is_valid_ember_frame_player)(metadata) return metadata, errors def extract_type_metadata(self, study_type): """ Pull the metadata related to the selected StudyType from the POST request """ type_fields = study_type.configuration["metadata"]["fields"] metadata = {} for key in type_fields: metadata[key] = self.request.POST.get(key, None) return metadata def is_valid_ember_frame_player(metadata): """Checks commit sha and player repo url. This must fulfill the contract of returning a list. We are exploiting the fact that empty lists evaluate falsey. :param metadata: the metadata object containing shas for both frameplayer and addons repo :type metadata: dict :return: a list of errors. :rtype: list. """ player_repo_url = metadata.get("player_repo_url", settings.EMBER_EXP_PLAYER_REPO) frameplayer_commit_sha = metadata.get("last_known_player_sha", "") errors = [] if not requests.get(player_repo_url).ok: errors.append(f"Frameplayer repo url {player_repo_url} does not work.") if not requests.get(f"{player_repo_url}/commit/{frameplayer_commit_sha}").ok: errors.append(f"Frameplayer commit {frameplayer_commit_sha} does not exist.") return errors VALIDATIONS = {"Ember Frame Player (default)": is_valid_ember_frame_player}
{ "repo_name": "CenterForOpenScience/lookit-api", "path": "exp/views/mixins.py", "copies": "1", "size": "6152", "license": "apache-2.0", "hash": 1407852026549908200, "line_mean": 34.3563218391, "line_max": 130, "alpha_frac": 0.6776657997, "autogenerated": false, "ratio": 4.120562625586068, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0011754008626538735, "num_lines": 174 }
from functools import cached_property, partial from logging import getLogger, FileHandler from multiprocessing import cpu_count from pathlib import Path from time import time from typing import Dict, Optional, Union, Sequence import albumentations as A import pytorch_lightning as pl from pytorch_lightning import seed_everything from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.loggers import TensorBoardLogger from torch.optim import Adam from torch.optim.lr_scheduler import LambdaLR, OneCycleLR from torch.utils.data import Dataset, DataLoader from torch_optimizer import RAdam from mobile_seg.dataset import load_df, MaskDataset, split_df from mobile_seg.loss import dice_loss from mobile_seg.modules.net import MobileNetV2_unet from mobile_seg.params import ModuleParams, Params, DataParams from mylib.albumentations.augmentations.transforms import MyCoarseDropout from mylib.pytorch_lightning.base_module import PLBaseModule, StepResult from mylib.pytorch_lightning.logging import configure_logging from mylib.torch.ensemble.ema import create_ema from mylib.torch.optim.sched import flat_cos # noinspection PyAbstractClass class DataModule(pl.LightningDataModule): def __init__(self, params: DataParams): super().__init__() self.params = params self.train_dataset: Optional[Dataset] = None self.val_dataset: Optional[Dataset] = None def setup(self, stage: Optional[str] = None): df = load_df() df_train, df_val = split_df(df, self.params) self.train_dataset = MaskDataset( df_train, transform=A.Compose([ A.RandomResizedCrop( self.params.img_size, self.params.img_size, ), A.Rotate(13), A.HorizontalFlip(), A.RandomBrightnessContrast(), A.HueSaturationValue(), A.RGBShift(), A.RandomGamma(), MyCoarseDropout( min_holes=1, max_holes=8, max_height=32, max_width=32, ), ]), ) self.val_dataset = MaskDataset( df_val, transform=A.Compose([ A.Resize( self.params.img_size, self.params.img_size, ), ]), ) def train_dataloader(self, *args, **kwargs) -> DataLoader: return DataLoader( self.train_dataset, batch_size=self.params.batch_size, shuffle=True, num_workers=cpu_count(), pin_memory=True, ) def val_dataloader(self, *args, **kwargs) -> Union[DataLoader, Sequence[DataLoader]]: return DataLoader( self.val_dataset, batch_size=self.params.batch_size, shuffle=False, num_workers=cpu_count(), pin_memory=True, ) # noinspection PyAbstractClass class PLModule(PLBaseModule[MobileNetV2_unet]): def __init__(self, hparams: Dict): super().__init__() self.hparams = hparams self.model = MobileNetV2_unet( drop_rate=self.hp.drop_rate, drop_path_rate=self.hp.drop_path_rate, ) self.criterion = dice_loss(scale=2) if self.hp.use_ema: self.ema_model = create_ema(self.model) def step(self, model: MobileNetV2_unet, batch) -> StepResult: X, y = batch y_hat = model.forward(X) # assert y.shape == y_hat.shape, f'{y.shape}, {y_hat.shape}' loss = self.criterion(y_hat, y) n_processed = len(y) return { 'loss': loss, 'n_processed': n_processed, } def configure_optimizers(self): params = self.model.parameters() if self.hp.optim == 'adam': opt = Adam( params, lr=self.hp.lr, weight_decay=self.hp.weight_decay, ) sched = { 'scheduler': OneCycleLR( opt, max_lr=self.hp.lr, total_steps=self.total_steps, ), 'interval': 'step', } elif self.hp.optim == 'radam': opt = RAdam( params, lr=self.hp.lr, weight_decay=self.hp.weight_decay, ) # noinspection PyTypeChecker sched = { 'scheduler': LambdaLR( opt, lr_lambda=partial( flat_cos, total_steps=self.total_steps, ), ), 'interval': 'step', } else: raise Exception return [opt], [sched] @cached_property def hp(self) -> ModuleParams: return ModuleParams.from_dict(dict(self.hparams)) def train(params: Params): seed_everything(params.d.seed) tb_logger = TensorBoardLogger( params.t.save_dir, name=f'mobile_seg', version=str(int(time())), ) log_dir = Path(tb_logger.log_dir) log_dir.mkdir(parents=True, exist_ok=True) logger = getLogger('lightning') logger.addHandler(FileHandler(log_dir / 'train.log')) logger.info(params.pretty()) trainer = pl.Trainer( max_epochs=params.t.epochs, gpus=params.t.gpus, tpu_cores=params.t.num_tpu_cores, logger=tb_logger, precision=params.t.precision, resume_from_checkpoint=params.t.resume_from_checkpoint, weights_save_path=params.t.save_dir, callbacks=[ # EarlyStopping( # monitor='ema_0_loss' if params.m.use_ema else 'val_0_loss', # patience=3, # mode='min' # ), ModelCheckpoint( monitor='ema_0_loss' if params.m.use_ema else 'val_0_loss', save_last=True, verbose=True, ), ], checkpoint_callback=True, deterministic=True, benchmark=True, ) net = PLModule(params.m.to_dict()) dm = DataModule(params.d) trainer.fit(net, datamodule=dm) if __name__ == '__main__': configure_logging() params = Params.load() if params.do_cv: for p in params.copy_for_cv(): train(p) else: train(params)
{ "repo_name": "akirasosa/mobile-semantic-segmentation", "path": "src/run_train.py", "copies": "1", "size": "6544", "license": "mit", "hash": 5138638162982190000, "line_mean": 29.5794392523, "line_max": 89, "alpha_frac": 0.551497555, "autogenerated": false, "ratio": 3.9162178336325555, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49677153886325554, "avg_score": null, "num_lines": null }
from functools import cmp_to_key from collections import namedtuple from common.deco import cachedprop, singleton from ..base import BinaryElementBase from ..location import UndefinedLocation class DataTypeBase(BinaryElementBase): def __init__(self, elf, name, loc_id): BinaryElementBase.__init__(self, elf) self.name = name self.loc_id = loc_id @property def location(self): if self.loc_id is not None: return self.elf.locations[self.loc_id] else: return UndefinedLocation @property def is_anonymous(self): '''True if the element is anonymous.''' return not self.name @property def safename(self): '''Name of the datatype or '<anonymous>' if anonymous.''' return self.name if not self.is_anonymous else '<anonymous>' class TypeInfo(DataTypeBase): def __init__(self, elf, parent_id, name, loc_id): DataTypeBase.__init__(self, elf, name, loc_id) self.parent_id = parent_id @property def parent(self): return self.elf.types[self.parent_id] class DataType(DataTypeBase): def __init__(self, elf, tid, kind, name, byte_size, inner_id, loc_id): DataTypeBase.__init__(self, elf, name, loc_id) self.tid = tid self.kind = kind self.byte_size = byte_size self.inner_id = inner_id def _get_is_scalar(self): return False def _get_printf_pattern(self): return '<dumping of %s is not supported>' % self @property def printf_pattern(self): return self._get_printf_pattern() def get_printf_elements(self, name): return [] def simple_printf(self, name): return '%s = ' + self.printf_pattern, ['"%s"' % name] + self.get_printf_elements(name) def simple_adbi_printf(self, name): fmt, args = self.simple_printf(name) if args < 1: return 'adbi_printf("' + fmt + '");' else: return 'adbi_printf("' + fmt + '", %s);' % ', '.join(args) @property def is_scalar(self): '''True for scalar data types, false for non-scalar data types. According to the C language specification, scalar types are types, which hold a single value, e.g. int, short, char, void, float and enum types. All other types are non-scalar, e.g. arrays, structs and unions. ''' return self._get_is_scalar() @property def bit_size(self): if self.byte_size is not None: return self.byte_size * 8 else: return None def get_codename(self): if self.is_anonymous: return '__adbi_anon_type_%06x' % self.tid else: return self.name def get_innermost_type(self): return self @property def innermost_type(self): return self.get_innermost_type() @property def codename(self): return self.get_codename() def define(self): raise NotImplementedError def declare(self): raise NotImplementedError def _define_var_type(self): yield self.innermost_type.codename def _define_var_name(self, name): return name @cachedprop def is_forwardable(self): '''True if the type can be forwarded.''' try: x = self.declare() return True except NotImplementedError: return False def define_var(self, name): spec = list(self._define_var_type()) if name is None: spec[-1] = '%s;' % (spec[-1]) else: spec[-1] = '%s %s;' % (spec[-1], self._define_var_name(name)) for line in spec: yield line def get_soft_requirements(self): return set() @cachedprop def soft_requirements(self): '''Set of datatypes, which must be at least declared to define this type.''' return self.get_soft_requirements() def get_hard_requirements(self): return set() @cachedprop def hard_requirements(self): '''Set of datatypes, which must be already defined to define this type.''' return self.get_hard_requirements() @cachedprop def requirements(self): '''Set of all datatypes, on which this type depends directly.''' return self.soft_requirements | self.hard_requirements @cachedprop def deforder(self): '''Return a list of tuples, which describe the datatypes on which this datatype depends. The types are sorted in the suggested order of definitions. The first element of each tuple is a datatype object. The second element is a boolean value, which is True if the type should be defined or False if the type only needs to be declared.''' TypeDeclaration = namedtuple('TypeDeclaration', 'type is_definition') ret = [] def is_declared(datatype): return is_defined(datatype) or TypeDeclaration(datatype, False) in ret def is_defined(datatype): return TypeDeclaration(datatype, True) in ret def process_type(datatype): if is_defined(datatype): # already defined return # insert all possible forward declarations for each in datatype.requirements: if each.is_forwardable and not is_declared(each): ret.append(TypeDeclaration(each, False)) # if possible, insert a forward declaration of the current type if datatype.is_forwardable and not is_declared(datatype): ret.append(TypeDeclaration(datatype, False)) # define all hard requirements for each in datatype.hard_requirements: process_type(each) for each in datatype.soft_requirements: if not each.is_forwardable and not is_defined(each): process_type(each) # define datatype assert all(is_defined(x) for x in datatype.hard_requirements) assert all(is_declared(x) for x in datatype.soft_requirements) ret.append(TypeDeclaration(datatype, True)) process_type(self) return ret def __str__(self): return self.safename def __repr__(self): return "<%s tid=%i %s>" % (self.__class__.__name__, self.tid, str(self)) class UnsupportedType(DataType): def get_codename(self): return 'void /* unsupported */'
{ "repo_name": "Samsung/ADBI", "path": "idk/cachereader/datatype/datatype.py", "copies": "1", "size": "6567", "license": "apache-2.0", "hash": 4164865685191119400, "line_mean": 29.123853211, "line_max": 104, "alpha_frac": 0.5954012487, "autogenerated": false, "ratio": 4.198849104859335, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5294250353559334, "avg_score": null, "num_lines": null }
from functools import cmp_to_key import string class Post: def __init__(self, image_id, unixtime, rawtime, reddit_id, subreddit, username): self.unixtime = unixtime self.rawtime = rawtime self.image_id = image_id self.reddit_id = reddit_id self.subreddit = subreddit self.username = username def __str__(self): t = "unixtime:" + self.unixtime + " rawtime:" + self.rawtime + " image_id:" + self.image_id + " reddit_id:" return t + self.reddit_id + " subreddit:" + self.subreddit + " username:" + self.username def StarndardizeTime(time): if '+' in time: time = time.split('+') timezone = time[1] time = time[0] if timezone == '00:00': return time timezone= timezone.split(":") time = time.split(":") hour = time[0] minute = time[1] second = time[2] elif '-' in time: time = time.spit('-') timezone = time[1] time = time[0] if timezone == '00:00': return time timezone= timezone.split(":") time = time.split(":") hour = time[0] minute = time[1] second = time[2] def SortViaTime(time1,time2): return false def SortDate(date1, date2): date1 = date1.split('-') date2 = date2.split('-') year1 = int(date1[0]) month1 = int(date1[1]) day1 = int(date1[2]) year2 = int(date2[0]) month2 = int(date2[1]) day2 = int(date2[2]) if year2 == year1: if month2 == month1: return day1 < day2 return month1 < month2 return year1 < year2 def SortViaRawTime(time1, time2): date1 = time1.split('T')[0] date2 = time2.split('T')[0] time1 = time1.split('T')[1] time2 = time2.split('T')[1] if date1 == date2: return SortViaTime(time1,time2) else: return SortDate(date1,date2) def LoadFile(filename): posts = [] counter = 0 with open(filename, 'r') as f: for line in f: line = line.split(',') if len(line) >= 13: if line[12].strip(): counter+=1 posts.append(Post(line[0], line[1], line[2], line[5], line[7], line[12])) print("Posts: " + str(counter)) return posts def CreateCascades(posts): cascades = {} for j in range(0, len(posts)): i = posts[j] t = [] if i.image_id in cascades.keys(): t = cascades[i.image_id] t.append(i) cascades[i.image_id] = t return cascades def StarndardizeTime(time): if '+' in time: time = time.split('+') timezone = time[1] time = time[0] if timezone == '00:00': return time timezone= timezone.split(":") time = time.split(":") hours = time[0] minutes = time[1] seconds = time[2] hoursplus = timezone[0] minutesplus = timezone[1] hours = int(hours) + int(hoursplus) minutes = int(minutes) + int(minutesplus) elif '-' in time: time = time.split('-') timezone = time[1] time = time[0] if timezone == '00:00': return time timezone= timezone.split(":") time = time.split(":") hours = time[0] minutes = time[1] seconds = time[2] hoursplus = timezone[0] minutesplus = timezone[1] hours = int(hours) - int(hoursplus) minutes = int(minutes) - int(minutesplus) return str(hours) + ":" + str(minutes) + ":" + str(seconds) def SortViaTime(time1,time2): time1 = time1.split(":") time2 = time2.split(":") if time1[0] == time2[0]: if time1[1] == time2[1]: if time1[2] == time2[2]: return 0 return time1[2] < time2[2] elif time1[1] < time2[1]: return -1 elif time1[1] > time2[1]: return 1 elif time1[0] < time2[0]: return -1 elif time1[0] > time2[0]: return 1 def SortDate(date1, date2): date1 = date1.split('-') date2 = date2.split('-') year1 = int(date1[0]) month1 = int(date1[1]) day1 = int(date1[2]) year2 = int(date2[0]) month2 = int(date2[1]) day2 = int(date2[2]) if year2 == year1: if month2 == month1: if day1 > day2: return 1 elif day1 < day2: return -1 else: return 0 elif month1 < month2: return -1 elif month1 > month2: return 1 elif year1 < year2: return -1 elif year1 > year2: return 1 def SortViaRawTime(ts,ts1): time1 = ts.rawtime time2 = ts1.rawtime date1 = time1.split('T')[0] date2 = time2.split('T')[0] time1 = time1.split('T')[1] time2 = time2.split('T')[1] if date1 == date2: time1 = StarndardizeTime(time1) time2 = StarndardizeTime(time2) return SortViaTime(time1,time2) else: return SortDate(date1,date2) def SortCascades(cascades): newcascades = {} for key in cascades: chain = cascades[key] newchain = sorted(chain, key=cmp_to_key(SortViaRawTime)) newcascades[key] = newchain return newcascades def PrintCascades(cascades, filename): for j in range(0,20): count = 0 total = 0 newcascades = {} username_to_id = {} for key in cascades: chain = cascades[key] if len(chain) > j: newcascades[key] = chain for key in newcascades: chain = newcascades[key] for i in chain: username_to_id[i.username.rstrip('\n')] = count count += 1 count = 0 with open(str(j)+filename, 'w') as f: for key in username_to_id: f.write(str(username_to_id[key]) + "," + str(username_to_id[key])+ "\n") f.write("\n") for key in newcascades: chain = newcascades[key] s = "" total += len(chain) count +=1 for i in chain: s = str(username_to_id[i.username.rstrip('\n')]) + "," + str(i.unixtime) + "," + s f.write(s[:-1] + "\n") print(str(total/count)) if __name__ == '__main__': posts = LoadFile('reddit.csv') cascades = CreateCascades(posts) sorted_cascades = SortCascades(cascades) PrintCascades(sorted_cascades, 'cascades.txt')
{ "repo_name": "dfcf93/RPICS", "path": "TheoryOfNetworkedSystems/Cascade-NETINF/Project Related/netinfredditprep.py", "copies": "1", "size": "6562", "license": "mit", "hash": -6486576776061138000, "line_mean": 30.2476190476, "line_max": 116, "alpha_frac": 0.5169155745, "autogenerated": false, "ratio": 3.3326561706449973, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4349571745144998, "avg_score": null, "num_lines": null }
from functools import cmp_to_key from oic.utils.http_util import extract_from_request __author__ = 'rolandh' UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" INTERNETPROTOCOLPASSWORD = \ 'urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword' MOBILETWOFACTORCONTRACT = \ 'urn:oasis:names:tc:SAML:2.0:ac:classes:MobileTwoFactorContract' PASSWORDPROTECTEDTRANSPORT = \ 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport' PASSWORD = 'urn:oasis:names:tc:SAML:2.0:ac:classes:Password' TLSCLIENT = 'urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient' TIMESYNCTOKEN = "urn:oasis:names:tc:SAML:2.0:ac:classes:TimeSyncToken" CMP_TYPE = ['exact', 'minimum', 'maximum', 'better'] class AuthnBroker(object): def __init__(self): self.db = {"info": {}, "key": {}} self.next = 0 @staticmethod def exact(a, b): return a == b @staticmethod def minimum(a, b): return b >= a @staticmethod def maximum(a, b): return b <= a @staticmethod def better(a, b): return b > a def add(self, acr, method, level=0, authn_authority=""): """ Adds a new authentication method. Assumes not more than one authentication method per type. :param acr: Add to what the authentication endpoint offers for this acr :param method: A identifier of the authentication method. :param level: security level, positive integers, 0 is lowest :return: """ _info = { "ref": acr, "method": method, "level": level, "authn_auth": authn_authority } self.next += 1 _ref = str(self.next) self.db["info"][_ref] = _info try: self.db["key"][acr].append(_ref) except KeyError: self.db["key"][acr] = [_ref] def remove(self, acr, method=None, level=0, authn_authority=""): try: _refs = self.db["key"][acr] except KeyError: return else: _remain = [] for _ref in _refs: item = self.db["info"][_ref] if method and method != item["method"]: _remain.append(_ref) if level and level != item["level"]: _remain.append(_ref) if authn_authority and \ authn_authority != item["authn_authority"]: _remain.append(_ref) if _remain: self.db[acr] = _remain @staticmethod def _cmp(item0, item1): v0 = item0[0] v1 = item1[0] if v0 > v1: return 1 elif v0 == v1: return 0 else: return -1 def _pick_by_class_ref(self, acr, comparision_type="exact"): func = getattr(self, comparision_type) try: _refs = self.db["key"][acr] except KeyError: return [] else: _info = self.db["info"] _item = _info[_refs[0]] _level = _item["level"] if comparision_type != "better": if _item["method"]: res = [(_level, _item["method"], _item["ref"])] else: res = [] else: res = [] for ref in _refs[1:]: item = _info[ref] res.append((item["level"], item["method"], item["ref"])) if func(_level, item["level"]): _level = item["level"] res_other = [] if comparision_type != "exact": for ref, _dic in _info.items(): if ref in _refs: continue elif func(_level, _dic["level"]): if _dic["method"]: _val = (_dic["level"], _dic["method"], _dic["ref"]) if _val not in res: res_other.append(_val) # sort on level res_other.sort(key=cmp_to_key(self._cmp), reverse=True) res.extend(res_other) return [(b, c) for a, b, c in res] def get_method(self, name): for key, item in self.db["info"].items(): if item["method"].__class__.__name__ == name: return item["method"] raise KeyError("No method by that name") def pick(self, acr=None, comparision_type="minimum"): """ Given the authentication context find zero or more places where the user could be sent next. Ordered according to security level. :param acr: The authentication class reference requested :param comparision_type: If the caller wants exact, at a minimum, ... this level :return: An URL """ if not comparision_type: comparision_type = "minimum" if acr is None: # Anything else doesn't make sense return self._pick_by_class_ref(UNSPECIFIED, "minimum") else: return self._pick_by_class_ref(acr, comparision_type) @staticmethod def match(requested, provided): if requested == provided: return True else: return False def __getitem__(self, item): i = 0 for key, info in self.db["info"].items(): if i == item: return info["method"], info["ref"] i += 1 raise IndexError() def getAcrValuesString(self): acr_values = None for item in self.db["info"].values(): if acr_values is None: acr_values = item["ref"] else: acr_values += " " + item["ref"] return acr_values def __iter__(self): for item in self.db["info"].values(): yield item["method"] raise StopIteration def __len__(self): return len(self.db["info"].keys()) def make_auth_verify(callback, next_module_instance=None): """ Closure encapsulating the next module (if any exist) in a multi auth chain. :param callback: function to execute for the callback URL at the OP, see UserAuthnMethod.verify and its subclasses (e.g. SAMLAuthnMethod) for signature :param next_module_instance: an object instance of the module next in the chain after the module whose verify method is the callback -- do not use this parameter!! If you want a multi auth chain see the convenience function setup_multi_auth (in multi_auth.py) :return: function encapsulating the specified callback which properly handles a multi auth chain. """ def auth_verify(environ, start_response, logger): kwargs = extract_from_request(environ) response, auth_is_complete = callback(**kwargs) if auth_is_complete and next_module_instance: response = next_module_instance(**kwargs) return response(environ, start_response) return auth_verify
{ "repo_name": "ekivemark/BlueButtonDev", "path": "oidc/pyoidc-master/src/oic/utils/authn/authn_context.py", "copies": "1", "size": "7079", "license": "apache-2.0", "hash": 8889058147749680000, "line_mean": 31.3287671233, "line_max": 120, "alpha_frac": 0.5376465602, "autogenerated": false, "ratio": 4.017593643586833, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5055240203786833, "avg_score": null, "num_lines": null }
from functools import cmp_to_key from sublime import Region from sublime_plugin import TextCommand class MoveTextHorizCommand(TextCommand): def move_text_horiz(self, edit, direction): for region in self.view.sel(): if region.empty(): continue orig_region = region sel_region = Region(region.begin() + direction, region.end() + direction) if sel_region.a < 0 or sel_region.b > self.view.size(): continue if direction < 0: dest_region = Region(region.begin() + direction, region.end()) move_text = self.view.substr(region) + self.view.substr(Region(region.begin() + direction, region.begin())) else: dest_region = Region(region.begin(), region.end() + direction) move_text = self.view.substr(Region(region.end(), region.end() + direction)) + self.view.substr(region) # Remove selection from RegionSet self.view.sel().subtract(orig_region) # Replace the selection with transformed text self.view.replace(edit, dest_region, move_text) # Add the new selection self.view.sel().add(sel_region) class MoveTextLeftCommand(MoveTextHorizCommand): def run(self, edit): self.move_text_horiz(edit, -1) class MoveTextRightCommand(MoveTextHorizCommand): def run(self, edit): self.move_text_horiz(edit, 1) class MoveTextVertCommand(TextCommand): def __init__(self, view): super(MoveTextVertCommand, self).__init__(view) view.move_text_vert_column = None def move_text_vert(self, region, edit, direction): if region.empty(): if direction < 0: self.view.run_command('swap_line_up') else: self.view.run_command('swap_line_down') return orig_region = region move_text = self.view.substr(region) # calculate number of characters to the left row, col = self.view.rowcol(region.begin()) # if the last command was a vertical move, use that column # the column is stored on the view - each command has its own instance, # and we don't want two buffers to modify the same object (e.g. MoveTextVertCommand) cmd, _, _ = self.view.command_history(0, True) if cmd != 'move_text_up' and cmd != 'move_text_down': self.view.move_text_vert_column = col elif self.view.move_text_vert_column: col = self.view.move_text_vert_column dest_row = row + direction max_row = self.view.rowcol(self.view.size())[0] if dest_row < 0: dest_row = 0 elif dest_row > max_row: dest_row = max_row self.view.sel().subtract(orig_region) self.view.replace(edit, region, '') # starting at the destination row at col 0, count off "col" characters # it's possible that there aren't enough characters in the destination row, # so stop if we end up on the wrong row, or past the buffer dest_point = self.view.text_point(dest_row, 0) if dest_point is None: dest_point = self.view.size() else: dest_line = self.view.line(dest_point) if dest_point + col > dest_line.b: dest_point = dest_line.b else: dest_point = dest_point + col insert_region = Region(dest_point, dest_point) sel_region = Region(dest_point, dest_point + len(move_text)) self.view.replace(edit, insert_region, move_text) self.view.sel().add(sel_region) self.view.show(sel_region) class MoveTextUpCommand(MoveTextVertCommand): def run(self, edit): for region in self.view.sel(): self.move_text_vert(region, edit, -1) class MoveTextDownCommand(MoveTextVertCommand): def run(self, edit): for region in self.view.sel(): self.move_text_vert(region, edit, 1)
{ "repo_name": "ggamir/SublimeMoveText", "path": "move_text.py", "copies": "1", "size": "4050", "license": "bsd-2-clause", "hash": -2310453472092009500, "line_mean": 34.8407079646, "line_max": 123, "alpha_frac": 0.5995061728, "autogenerated": false, "ratio": 3.817153628652215, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9914417181694873, "avg_score": 0.0004485239514682716, "num_lines": 113 }
from functools import cmp_to_key import mufsim.utils as util import mufsim.gamedb as db import mufsim.stackitems as si from mufsim.errors import MufRuntimeError from mufsim.insts.base import Instruction, instr @instr("addprop") class InstAddProp(Instruction): def execute(self, fr): fr.check_underflow(3) val2 = fr.data_pop(int) val = fr.data_pop(str) prop = fr.data_pop(str) obj = fr.data_pop_object() if val: obj.setprop(prop, val) else: obj.setprop(prop, val2) @instr("setprop") class InstSetProp(Instruction): def execute(self, fr): fr.check_underflow(3) val = fr.data_pop() prop = fr.data_pop(str) obj = fr.data_pop_object() obj.setprop(prop, val) @instr("remove_prop") class InstRemoveProp(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() obj.delprop(prop) @instr("propdir?") class InstPropDirP(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.is_propdir(prop) fr.data_push(1 if val else 0) @instr("nextprop") class InstNextProp(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.next_prop(prop) fr.data_push(val) @instr("array_get_propdirs") class InstArrayGetPropDirs(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) + '/' obj = fr.data_pop_object() out = [] while True: prop = obj.next_prop(prop) if not prop: break if obj.is_propdir(prop): out.append(prop) fr.data_push_list(out) @instr("getprop") class InstGetProp(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if val is None: val = 0 fr.data_push(val) @instr("getpropstr") class InstGetPropStr(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, str): val = "" fr.data_push(val) @instr("getpropval") class InstGetPropVal(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, int): val = 0 fr.data_push(val) @instr("getpropfval") class InstGetPropFVal(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, float): val = 0.0 fr.data_push(val) @instr("envprop") class InstEnvProp(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object().dbref while obj >= 0: val = db.getobj(obj).getprop(prop) if val is not None: break obj = db.getobj(obj).location if val is None: val = 0 fr.data_push(val) @instr("envpropstr") class InstEnvPropStr(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object().dbref while obj >= 0: val = db.getobj(obj).getprop(prop) if val is not None: break obj = db.getobj(obj).location if isinstance(val, str): fr.data_push(val) else: fr.data_push("") @instr("blessprop") class InstBlessProp(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() obj.blessprop(prop) @instr("unblessprop") class InstUnBlessProp(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() obj.unblessprop(prop) @instr("blessed?") class InstBlessedP(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.is_blessed(prop) fr.data_push(1 if val else 0) @instr("array_get_proplist") class InstArrayGetPropList(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() out = [] val = obj.getprop("%s#" % prop) cnt = 0 if val: if isinstance(val, str): try: cnt = int(cnt) except: cnt = 0 elif isinstance(val, int): cnt = val for i in range(cnt): val = obj.getprop("%s#/%d" % (prop, i + 1)) if isinstance(val, str): out.append(val) fr.data_push_list(out) @instr("array_put_proplist") class InstArrayPutPropList(Instruction): def execute(self, fr): fr.check_underflow(3) items = fr.data_pop_list() prop = fr.data_pop(str) obj = fr.data_pop_object() obj.setprop("%s#" % prop, len(items)) for i, item in enumerate(items[:]): obj.setprop("%s#/%d" % (prop, i + 1), item) @instr("array_get_propvals") class InstArrayGetPropVals(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() prop = obj.normalize_prop(prop) + '/' plen = len(prop) out = {} vprop = obj.next_prop(prop) while vprop: val = obj.getprop(vprop) if val is not None: out[vprop[plen:]] = val vprop = obj.next_prop(vprop) fr.data_push_dict(out) @instr("array_put_propvals") class InstArrayPutPropVals(Instruction): def execute(self, fr): fr.check_underflow(3) d = fr.data_pop_dict() prop = fr.data_pop(str) obj = fr.data_pop_object() keys = sorted( list(d.keys()), key=cmp_to_key(si.sortcomp), ) for key in keys: obj.setprop("%s/%s" % (prop, key), d[key]) @instr("array_get_reflist") class InstArrayGetReflist(Instruction): def execute(self, fr): fr.check_underflow(2) prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, str): fr.data_push_list([]) else: vals = [ si.DBRef(int(x[1:])) for x in val.split(" ") if util.is_dbref(x) ] fr.data_push_list(vals) @instr("array_put_reflist") class InstArrayPutReflist(Instruction): def execute(self, fr): fr.check_underflow(3) refs = fr.data_pop_list() prop = fr.data_pop(str) obj = fr.data_pop_object() fr.check_list_type(refs, (si.DBRef), argnum=3) refstr = " ".join([str(ref) for ref in refs]) obj.setprop(prop, refstr) @instr("reflist_add") class InstRefListAdd(Instruction): def execute(self, fr): fr.check_underflow(3) ref = fr.data_pop_dbref() prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, str): refs = [] else: refs = [ si.DBRef(int(x[1:])) for x in val.split(" ") if util.is_dbref(x) ] while ref in refs: del refs[refs.index(ref)] refs.append(ref) refstr = " ".join([str(x) for x in refs]) obj.setprop(prop, refstr) @instr("reflist_del") class InstRefListDel(Instruction): def execute(self, fr): fr.check_underflow(3) ref = fr.data_pop_dbref() prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, str): refs = [] else: refs = [ si.DBRef(int(x[1:])) for x in val.split(" ") if util.is_dbref(x) ] while ref in refs: del refs[refs.index(ref)] refstr = " ".join([str(x) for x in refs]) obj.setprop(prop, refstr) @instr("reflist_find") class InstRefListFind(Instruction): def execute(self, fr): fr.check_underflow(3) ref = fr.data_pop_dbref() prop = fr.data_pop(str) obj = fr.data_pop_object() val = obj.getprop(prop) if not isinstance(val, str): refs = [] else: refs = [ si.DBRef(int(x[1:])) for x in val.split(" ") if util.is_dbref(x) ] if ref in refs: fr.data_push(refs.index(ref) + 1) else: fr.data_push(0) @instr("array_filter_prop") class InstArrayFilterProp(Instruction): def execute(self, fr): fr.check_underflow(3) pat = fr.data_pop(str) prop = fr.data_pop(str) objs = fr.data_pop_list() found = [] fr.check_list_type(objs, (si.DBRef), argnum=1) for obj in objs: if db.validobj(obj): val = db.getobj(obj).getprop(prop) if val and util.smatch(pat, val): found.append(obj) fr.data_push_list(found) @instr("array_filter_flags") class InstArrayFilterFlags(Instruction): def execute(self, fr): fr.check_underflow(2) flags = fr.data_pop(str).upper() objs = fr.data_pop_list() fr.check_list_type(obj, (si.DBRef), argnum=1) found = [] for obj in objs: if db.validobj(obj): obj = db.getobj(obj) if db.flagsmatch(flags, obj): found.append(si.DBRef(obj.dbref)) fr.data_push_list(found) # vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
{ "repo_name": "revarbat/mufsim", "path": "mufsim/insts/properties.py", "copies": "1", "size": "10436", "license": "bsd-2-clause", "hash": -7676189149316034000, "line_mean": 25.9664082687, "line_max": 60, "alpha_frac": 0.5344001533, "autogenerated": false, "ratio": 3.336317135549872, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43707172888498724, "avg_score": null, "num_lines": null }
from functools import lru_cache as _lru_cache import string as _string import pearl as _pearl from . import ast as _ast g = _pearl.Grammar() g = g.put('__start__', [{'statement_sequence'}, 'whitespace']) # statement sequence g = g.put('statement_sequence', [{'statements'}], _ast.StatementSequence) g = g.put('statements', [], lambda: ()) g = g.put('statements', [{'statement'}, {'statements'}], lambda first, rest: (first,) + rest) # unused expression g = g.put('statement', [{'expression'}, 'whitespace', ';']) # export g = g.put('export', [], lambda: False) g = g.put('export', ['whitespace', 'e', 'x', 'p', 'o', 'r', 't'], lambda: True) @_lru_cache(maxsize=256) def _get_grammar_patch(module_path): from ._read import read module_body = read(module_path) patches = [] for s in module_body.statements: if s.__class__ == _ast.MacroDefinition and s.exported: patches.append((lambda s: lambda g: _add_macro_use_rule(g, s.nonterminal, s.parameters))(s)) if s.__class__ == _ast.MacroUndefinition and s.exported: patches.append((lambda s: lambda g: _drop_unmacro_rule(g, s.nonterminal, s.parameters))(s)) def patch_grammar(g): for patch in patches: g = patch(g) return g return patch_grammar # import g = g.put('statements', [{'export'}, 'whitespace', 'i', 'm', 'p', 'o', 'r', 't', {'string'}, 'whitespace', ';', (lambda g, exported, module_path: _get_grammar_patch(module_path)(g)), {'statements'}], lambda exported, module_path, rest: (_ast.Import(exported, module_path),) + rest) # variable declaration g = g.put('statement', [{'export'}, 'whitespace', 'v', 'a', 'r', {'identifier'}, 'whitespace', ';'], _ast.VariableDeclaration) def _build_macro_body_symbols(parameters): body_symbols = [] for parameter in parameters: if parameter.__class__ == _ast.MacroParameterTerminal: body_symbols.extend(parameter.symbols) else: assert parameter.__class__ == _ast.MacroParameterNonterminal body_symbol = parameter.symbol if len(body_symbol) == 1: body_symbol += '-one-char-nonterminal' if parameter.name is not None: body_symbol = {body_symbol} body_symbols.append(body_symbol) return body_symbols def _add_macro_use_rule(g, head, body): return g.put(head, _build_macro_body_symbols(body), lambda *nodes: _ast.MacroUse(head, body, nodes)) def _build_macro_transform(parameters, transform_body): arguments = ['__usage_context__'] for parameter in parameters: if parameter.__class__ == _ast.MacroParameterNonterminal and parameter.name is not None: arguments.append(parameter.name) return _ast.FunctionLiteral(tuple(arguments), transform_body) # macro definition g = g.put('statements', [{'export'}, 'whitespace', 'm', 'a', 'c', 'r', 'o', {'identifier'}, 'whitespace', '-', '>', {'macro_parameters'}, 'whitespace', '{', {'statement_sequence'}, 'whitespace', '}', (lambda g, exported, head, body, _: _add_macro_use_rule(g, head, body)), {'statements'}], lambda exported, head, body, transform_body, rest: (_ast.MacroDefinition(exported, head, body, _build_macro_transform(body, transform_body)),) + rest) g = g.put('macro_parameters', [], lambda: ()) g = g.put('macro_parameters', [{'macro_parameter'}], lambda parameter: (parameter,)) g = g.put('macro_parameters', [{'macro_parameter'}, 'whitespace', ',', {'macro_parameters'}], lambda first, rest: (first,) + rest) g = g.put('macro_parameter', [{'string'}], lambda symbols: _ast.MacroParameterTerminal(tuple(symbols))) g = g.put('macro_parameter', [{'identifier'}, {'macro_parameter_nonterminal_name'}], _ast.MacroParameterNonterminal) g = g.put('macro_parameter_nonterminal_name', [], lambda: None) g = g.put('macro_parameter_nonterminal_name', ['whitespace', '/', {'identifier'}]) def _drop_unmacro_rule(g, head, body): return g.drop(head, _build_macro_body_symbols(body)) # unmacro g = g.put('statements', [{'export'}, 'whitespace', 'u', 'n', 'm', 'a', 'c', 'r', 'o', {'identifier'}, 'whitespace', '-', '>', {'unmacro_parameters'}, 'whitespace', ';', (lambda g, exported, head, body: _drop_unmacro_rule(g, head, body)), {'statements'}], lambda exported, head, body, rest: (_ast.MacroUndefinition(exported, head, body),) + rest) g = g.put('unmacro_parameters', [], lambda: ()) g = g.put('unmacro_parameters', [{'unmacro_parameter'}], lambda parameter: (parameter,)) g = g.put('unmacro_parameters', [{'unmacro_parameter'}, 'whitespace', ',', {'unmacro_parameters'}], lambda first, rest: (first,) + rest) g = g.put('unmacro_parameter', [{'string'}], lambda symbols: _ast.MacroParameterTerminal(tuple(symbols))) g = g.put('unmacro_parameter', [{'identifier'}], lambda symbol: _ast.MacroParameterNonterminal(symbol, None)) # block g = g.put('statement', [{'block'}]) g = g.put('block', ['whitespace', '{', {'statement_sequence'}, 'whitespace', '}'], _ast.Block) # if g = g.put('statement', [{'if'}]) g = g.put('if', ['whitespace', 'i', 'f', {'expression'}, {'block'}, {'if_else'}], _ast.If) g = g.put('if_else', ['whitespace', 'e', 'l', 's', 'e', {'block'}]) # forever g = g.put('statement', [{'forever'}]) g = g.put('forever', ['whitespace', 'f', 'o', 'r', 'e', 'v', 'e', 'r', {'block'}], _ast.Forever) # continue g = g.put('statement', [{'continue'}]) g = g.put('continue', ['whitespace', 'c', 'o', 'n', 't', 'i', 'n', 'u', 'e', 'whitespace', ';'], _ast.Continue) # break g = g.put('statement', [{'break'}]) g = g.put('break', ['whitespace', 'b', 'r', 'e', 'a', 'k', 'whitespace', ';'], _ast.Break) # return g = g.put('statement', [{'return'}]) g = g.put('return', ['whitespace', 'r', 'e', 't', 'u', 'r', 'n', {'expression'}, 'whitespace', ';'], _ast.Return) # variable assignment g = g.put('statement', [{'variable_assignment'}]) g = g.put('variable_assignment', [{'identifier'}, 'whitespace', '=', {'expression'}, 'whitespace', ';'], _ast.VariableAssignment) # attribute assignment g = g.put('statement', [{'attribute_assignment'}]) g = g.put('attribute_assignment', [{'postfix_expression'}, 'whitespace', '.', {'identifier'}, 'whitespace', '=', {'expression'}, 'whitespace', ';'], _ast.AttributeAssignment) g = g.put('expression', [{'postfix_expression'}]) # attribute access g = g.put('postfix_expression', [{'attribute_access'}]) g = g.put('attribute_access', [{'postfix_expression'}, 'whitespace', '.', {'identifier'}], _ast.AttributeAccess) # call g = g.put('postfix_expression', [{'call'}]) g = g.put('call', [{'postfix_expression'}, 'whitespace', '(', {'call_arguments'}, 'whitespace', ')'], _ast.Call) g = g.put('call_arguments', [], lambda: ()) g = g.put('call_arguments', [{'expression'}], lambda argument: (argument,)) g = g.put('call_arguments', [{'expression'}, 'whitespace', ',', {'call_arguments'}], lambda argument, rest: (argument,) + rest) g = g.put('postfix_expression', [{'primary_expression'}]) # variable access g = g.put('primary_expression', [{'variable_access'}]) g = g.put('variable_access', [{'identifier'}], _ast.VariableAccess) # number literal g = g.put('primary_expression', [{'number_literal'}]) g = g.put('number_literal', [{'number'}], _ast.NumberLiteral) # string literal g = g.put('primary_expression', [{'string_literal'}]) g = g.put('string_literal', [{'string'}], _ast.StringLiteral) # function literal g = g.put('primary_expression', [{'function_literal'}]) g = g.put('function_literal', ['whitespace', '(', {'function_literal_parameters'}, 'whitespace', ')', 'whitespace', '=', '>', 'whitespace', '{', {'statement_sequence'}, 'whitespace', '}'], _ast.FunctionLiteral) g = g.put('function_literal_parameters', [], lambda: ()) g = g.put('function_literal_parameters', [{'identifier'}], lambda parameter: (parameter,)) g = g.put('function_literal_parameters', [{'identifier'}, 'whitespace', ',', {'function_literal_parameters'}], lambda first, rest: (first,) + rest) # parenthesized expression g = g.put('primary_expression', [{'parenthesized_expression'}]) g = g.put('parenthesized_expression', ['whitespace', '(', {'expression'}, 'whitespace', ')']) def parse_string(text): return text[1:-1]. \ replace('\\\\', '\\'). \ replace('\\\'', '\''). \ replace('\\\t', '\t'). \ replace('\\\v', '\v'). \ replace('\\\f', '\f'). \ replace('\\\n', '\n'). \ replace('\\\r', '\r') g = g.put('string', ['whitespace', {'string_without_whitespace'}], parse_string) g = g.put('string_without_whitespace', ['\'', 'string_items', '\'']) g = g.put('string_items', []) g = g.put('string_items', ['string_item', 'string_items']) g = g.put('string_item', ['letter']) g = g.put('string_item', ['digit']) g = g.put('string_item', ['punctuation_without_backslash_and_quote']) g = g.put('string_item', ['\\', '\\']) g = g.put('string_item', ['\\', '\'']) g = g.put('string_item', ['whitespace_char']) g = g.put('string_item', ['\\', 't']) g = g.put('string_item', ['\\', 'v']) g = g.put('string_item', ['\\', 'f']) g = g.put('string_item', ['\\', 'n']) g = g.put('string_item', ['\\', 'r']) g = g.put('number', ['whitespace', {'number_without_whitespace'}], float) g = g.put('number_without_whitespace', ['number_sign_opt', 'number_integer', 'number_fraction_opt', 'number_exponent_opt']) g = g.put('number_sign_opt', []) g = g.put('number_sign_opt', ['+']) g = g.put('number_sign_opt', ['-']) g = g.put('number_integer', ['digit']) g = g.put('number_integer', ['digit', 'number_integer']) g = g.put('number_fraction_opt', []) g = g.put('number_fraction_opt', ['.', 'number_integer']) g = g.put('number_exponent_opt', []) g = g.put('number_exponent_opt', ['e', 'number_sign_opt', 'number_integer']) g = g.put('number_exponent_opt', ['E', 'number_sign_opt', 'number_integer']) g = g.put('identifier', ['whitespace', {'identifier_without_whitespace'}]) g = g.put('identifier_without_whitespace', ['identifier_head', 'identifier_tail']) g = g.put('identifier_head', ['_']) g = g.put('identifier_head', ['letter']) g = g.put('identifier_tail', []) g = g.put('identifier_tail', ['_', 'identifier_tail']) g = g.put('identifier_tail', ['letter', 'identifier_tail']) g = g.put('identifier_tail', ['digit', 'identifier_tail']) # comment g = g.put('whitespace', ['#', 'comment_chars', '\n', 'whitespace']) g = g.put('comment_chars', []) g = g.put('comment_chars', ['comment_char', 'comment_chars']) g = g.put('comment_char', ['letter']) g = g.put('comment_char', ['digit']) g = g.put('comment_char', ['punctuation']) g = g.put('comment_char', ['whitespace_char_without_newline']) for c in _string.ascii_letters: g = g.put('letter', [c]) for c in _string.digits: g = g.put('digit', [c]) for c in _string.punctuation: if c not in '\\\'': g = g.put('punctuation_without_backslash_and_quote', [c]) g = g.put('punctuation', ['punctuation_without_backslash_and_quote']) g = g.put('punctuation', ['\\']) g = g.put('punctuation', ['\'']) g = g.put('whitespace_without_newline', []) g = g.put('whitespace_without_newline', ['whitespace_char_without_newline', 'whitespace_without_newline']) for c in _string.whitespace: if c != '\n': g = g.put('whitespace_char_without_newline', [c]) g = g.put('whitespace', []) g = g.put('whitespace', ['whitespace_char', 'whitespace']) g = g.put('whitespace_char', ['whitespace_char_without_newline']) g = g.put('whitespace_char', ['\n']) core_grammar = g del g
{ "repo_name": "yuri-kilochek/pearl", "path": "lang/core/_core_grammar.py", "copies": "1", "size": "13446", "license": "mit", "hash": 3533470019055960600, "line_mean": 36.041322314, "line_max": 192, "alpha_frac": 0.5227576975, "autogenerated": false, "ratio": 3.7112889870273253, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47340466845273255, "avg_score": null, "num_lines": null }
from functools import lru_cache as _lru_cache from ._read import read as _read from . import ast as _ast @_lru_cache(maxsize=None) class Module: def __init__(self, path): self.__path = path self.__body = _read(path) self.__exported_variables = {} self.__exported_macro_definitions = {} context = _ast.Context() self.__body.execute(context) for s in self.__body.statements: if s.__class__ == _ast.Import and s.exported: module = Module(s.module_path) self.__exported_variables.update(module.__exported_variables) self.__exported_macro_definitions.update(module.__exported_macro_definitions) if s.__class__ == _ast.VariableDeclaration and s.exported: name = s.name self.__exported_variables[name] = context.variables[name] if s.__class__ == _ast.MacroDefinition and s.exported: rule = s.nonterminal, s.parameters self.__exported_macro_definitions[rule] = context.macro_definitions[rule] if self.__path in _builtin_modules: self.__exported_variables.update(_builtin_modules[self.__path]) @property def path(self): return self.__path @property def body(self): return self.__body @property def exported_variables(self): return self.__exported_variables @property def exported_macro_definitions(self): return self.__exported_macro_definitions _builtin_modules = { '/std/types': { 'None': None, 'bool': bool, 'False': False, 'True': True, 'int': int, 'str': str, 'list': list, 'dict': dict, 'tuple': tuple, 'set': set, 'frozenset': frozenset, 'slice': slice, }, '/std/io': { 'input': input, 'print': print, }, '/std/ast': {n: v for n, v in _ast.__dict__.items() if not n.startswith('_')}, }
{ "repo_name": "yuri-kilochek/pearl", "path": "lang/core/_Module.py", "copies": "1", "size": "2020", "license": "mit", "hash": 8749961458645973000, "line_mean": 27.8571428571, "line_max": 93, "alpha_frac": 0.553960396, "autogenerated": false, "ratio": 4.031936127744511, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5085896523744511, "avg_score": null, "num_lines": null }
from functools import lru_cache class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: MOD = 10 ** 9 + 7 @lru_cache(None) def dfs(prevSame, curr, left): if left == 0: return 1 total = 0 for i in range(6): if curr != i: total = (total + dfs(1, i, left - 1)) % MOD elif prevSame < rollMax[i]: total = (total + dfs(prevSame + 1, i, left - 1)) % MOD return total return dfs(0, 0, n) class Solution2: def dieSimulator(self, n: int, rollMax: List[int]) -> int: MOD = 10 ** 9 + 7 dp = [[1] * 7 for _ in range(n)] dp[0][6] = 6 for i in range(1, n): total = 0 for j in range(6): dp[i][j] = dp[i - 1][6] if i > rollMax[j]: reduction = (dp[i - rollMax[j] - 1][6] - dp[i - rollMax[j] - 1][j]) % MOD dp[i][j] = (dp[i][j] - reduction) % MOD elif i == rollMax[j]: dp[i][j] = (dp[i][j] - 1) % MOD total = (total + dp[i][j]) % MOD dp[i][6] = total return dp[n - 1][6]
{ "repo_name": "jiadaizhao/LeetCode", "path": "1201-1300/1223-Dice Roll Simulation/1223-Dice Roll Simulation.py", "copies": "1", "size": "1252", "license": "mit", "hash": 1295571516814218000, "line_mean": 31.9473684211, "line_max": 93, "alpha_frac": 0.4065495208, "autogenerated": false, "ratio": 3.3297872340425534, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42363367548425535, "avg_score": null, "num_lines": null }
from functools import lru_cache class Solution: def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int: m = len(evil) lps = [0] * m i = 1 l = 0 while i < m: if evil[i] == evil[l]: lps[i] = l + 1 i += 1 l += 1 elif l != 0: l = lps[l - 1] else: i += 1 MOD = 10 ** 9 + 7 @lru_cache(None) def dfs(start, pre1, pre2, preE): if preE == m: return 0 if start == n: return 1 total = 0 first = ord(s1[start]) if pre1 else ord('a') last = ord(s2[start]) if pre2 else ord('z') for ci in range(first, last + 1): c = chr(ci) _pre1 = pre1 and ci == first _pre2 = pre2 and ci == last _preE = preE while _preE and c != evil[_preE]: _preE = lps[_preE - 1] if c == evil[_preE]: _preE += 1 total += dfs(start + 1, _pre1, _pre2, _preE) total %= MOD return total return dfs(0, True, True, 0)
{ "repo_name": "jiadaizhao/LeetCode", "path": "1301-1400/1397-Find All Good Strings/1397-Find All Good Strings.py", "copies": "1", "size": "1337", "license": "mit", "hash": 8436892174953766000, "line_mean": 27.4468085106, "line_max": 74, "alpha_frac": 0.3500373972, "autogenerated": false, "ratio": 3.7982954545454546, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9563069034807423, "avg_score": 0.01705276338760603, "num_lines": 47 }
from functools import lru_cache from bisect import bisect_left from Levenshtein import distance from .hashable_list_wrapper import HashableListWrapper def _index(container, value): """ Locate the leftmost value exactly equal to x """ i = bisect_left(container, value) if i != len(container) and container[i] == value: return i raise ValueError def _contains(container, value): """ Contains value exactly equal to x """ try: _index(container, value) return True except ValueError: return False def prepare_dictionary(words, first_letter_group=True): """ Returns dictionary :param words: collection of strings :param first_letter_group: group to dictiionary by first letter? :return: dictionary :rtype: dict[str, list[str]]|list[str] """ if not first_letter_group: result = list(words) result.sort() return result else: result = {} letters = set([word[0] for word in words]) for letter in letters: result[letter] = [] for word in words: result[word[0]].append(word) for letter in letters: result[letter].sort() return result @lru_cache(maxsize=1000) def _correct(word, words_to_search, min_correction_length, max_distance): assert len(word) > 0 if _contains(words_to_search, word): return word if len(word) < min_correction_length: return None found_words = [] found_distance = -1 for iter_word in words_to_search: iter_distance = distance(word, iter_word) if len(found_words) == 0 or found_distance > iter_distance: found_words = [iter_word] found_distance = iter_distance elif found_distance == iter_distance: found_words.append(iter_word) if found_distance > max_distance: return None return found_words[0] def correct(word, dictionary, min_correction_length=3, max_distance=4): """ Correct word (if have mistake) :param word: word :type word: str :param dictionary: dictionary object : [firstLetter]->words \ or just words. Words must be ordered. :type dictionary: dict[str, list[str]]|list[str] :param max_distance: maximum distance :type max_distance: int :return: word or None :rtype: str """ if isinstance(dictionary, dict): words_to_search = dictionary[word[0]] else: words_to_search = dictionary return _correct(word, HashableListWrapper(words_to_search), min_correction_length, max_distance)
{ "repo_name": "b09dan/universities_sentiment", "path": "text_class/pynlc/corrector.py", "copies": "1", "size": "2644", "license": "mit", "hash": -8119757400422923000, "line_mean": 28.3777777778, "line_max": 73, "alpha_frac": 0.628214826, "autogenerated": false, "ratio": 3.9345238095238093, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00037037037037037035, "num_lines": 90 }