code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def submissionfile_post_save(sender, instance, signal, created, **kwargs): ''' Update MD5 field for newly uploaded files. ''' if created: logger.debug("Running post-processing for new submission file.") instance.md5 = instance.attachment_md5() instance.save(f submissionfile_p...
Update MD5 field for newly uploaded files.
def schedule(self, recipients=None, sender=None, priority=None): if priority is None: priority = self.priority self._message_model, self._dispatch_models = Message.create( self.get_alias(), self.get_context(), recipients=recipients, sender=sender, priority=priority ...
Schedules message for a delivery. Puts message (and dispatches if any) data into DB. :param list|None recipients: recipient (or a list) or None. If `None` Dispatches should be created before send using `prepare_dispatches()`. :param User|None sender: Django User model heir instance ...
def get_subscribers(cls, active_only=True): subscribers_raw = Subscription.get_for_message_cls(cls.alias) subscribers = [] for subscriber in subscribers_raw: messenger_cls = subscriber.messenger_cls address = subscriber.address recipient = subscriber...
Returns a list of Recipient objects subscribed for this message type. :param bool active_only: Flag whether :return:
def _get_url(cls, name, message_model, dispatch_model): global APP_URLS_ATTACHED url = '' if dispatch_model is None: return url if APP_URLS_ATTACHED != False: # sic! hashed = cls.get_dispatch_hash(dispatch_model.id, message_model.id) try...
Returns a common pattern sitemessage URL. :param str name: URL name :param Message message_model: :param Dispatch|None dispatch_model: :return:
def handle_unsubscribe_request(cls, request, message, dispatch, hash_is_valid, redirect_to): if hash_is_valid: Subscription.cancel( dispatch.recipient_id or dispatch.address, cls.alias, dispatch.messenger ) signal = sig_unsubscribe_success el...
Handles user subscription cancelling request. :param Request request: Request instance :param Message message: Message model instance :param Dispatch dispatch: Dispatch model instance :param bool hash_is_valid: Flag indicating that user supplied request signature is correct :par...
def handle_mark_read_request(cls, request, message, dispatch, hash_is_valid, redirect_to): if hash_is_valid: dispatch.mark_read() dispatch.save() signal = sig_mark_read_success else: signal = sig_mark_read_failed signal.send(cls, request...
Handles a request to mark a message as read. :param Request request: Request instance :param Message message: Message model instance :param Dispatch dispatch: Dispatch model instance :param bool hash_is_valid: Flag indicating that user supplied request signature is correct :para...
def get_template(cls, message, messenger): template = message.context.get('tpl', None) if template: # Template name is taken from message context. return template if cls.template is None: cls.template = 'sitemessage/messages/%s__%s.%s' % ( cls....
Get a template path to compile a message. 1. `tpl` field of message context; 2. `template` field of message class; 3. deduced from message, messenger data and `template_ext` message type field (e.g. `sitemessage/messages/plain__smtp.txt` for `plain` message type). :param Mes...
def compile(cls, message, messenger, dispatch=None): if message.context.get('use_tpl', False): context = message.context context.update({ 'SITE_URL': get_site_url(), 'directive_unsubscribe': cls.get_unsubscribe_directive(message, dispatch), ...
Compiles and returns a message text. Considers `use_tpl` field from message context to decide whether template compilation is used. Otherwise a SIMPLE_TEXT_ID field from message context is used as message contents. :param Message message: model instance :param MessengerBase me...
def update_context(cls, base_context, str_or_dict, template_path=None): if isinstance(str_or_dict, dict): base_context.update(str_or_dict) base_context['use_tpl'] = True else: base_context[cls.SIMPLE_TEXT_ID] = str_or_dict if cls.SIMPLE_TEXT_ID in st...
Helper method to structure initial message context data. NOTE: updates `base_context` inplace. :param dict base_context: context dict to update :param dict, str str_or_dict: text representing a message, or a dict to be placed into message context. :param str template_path: template pat...
def prepare_dispatches(cls, message, recipients=None): return Dispatch.create(message, recipients or cls.get_subscribers())
Creates Dispatch models for a given message and return them. :param Message message: Message model instance :param list|None recipients: A list or Recipient objects :return: list of created Dispatch models :rtype: list
def get_page_access_token(self, app_id, app_secret, user_token): url_extend = ( self._url_base + '/oauth/access_token?grant_type=fb_exchange_token&' 'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s') response = self.li...
Returns a dictionary of never expired page token indexed by page names. :param str app_id: Application ID :param str app_secret: Application secret :param str user_token: User short-lived token :rtype: dict
def create_working_dir(config, prefix): ''' Create a fresh temporary directory, based on the fiven prefix. Returns the new path. ''' # Fetch base directory from executor configuration basepath = config.get("Execution", "directory") if not prefix: prefix = 'opensubmit' f...
Create a fresh temporary directory, based on the fiven prefix. Returns the new path.
def django_admin(args): ''' Run something like it would be done through Django's manage.py. ''' from django.core.management import execute_from_command_line from django.core.exceptions import ImproperlyConfigured os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opensubmit.settings") try:...
Run something like it would be done through Django's manage.py.
def apache_config(config, outputfile): ''' Generate a valid Apache configuration file, based on the given settings. ''' if os.path.exists(outputfile): os.rename(outputfile, outputfile + ".old") print("Renamed existing Apache config file to " + outputfile + ".old") from django.co...
Generate a valid Apache configuration file, based on the given settings.
def check_path(file_path): ''' Checks if the directories for this path exist, and creates them in case. ''' directory = os.path.dirname(file_path) if directory != '': if not os.path.exists(directory): os.makedirs(directory, 0o775f check_path(file_path): ''' Checks...
Checks if the directories for this path exist, and creates them in case.
def check_file(filepath): ''' - Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific. ''' check_path(filepath) if not os.path.exists(filepath): print...
- Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific.
def check_web_config(config_fname): ''' Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None. ''' print("Looking for config file at {0} ...".format(config_fname)) config = RawConfigParser() ...
Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None.
def normalize_url(url: str) -> str: if url.startswith('/'): url = url[1:] if url.endswith('/'): url = url[:-1] return url
Remove leading and trailing slashes from a URL :param url: URL :return: URL with no leading and trailing slashes :private:
def _unwrap(variable_parts: VariablePartsType): curr_parts = variable_parts var_any = [] while curr_parts: curr_parts, (var_type, part) = curr_parts if var_type == Routes._VAR_ANY_NODE: var_any.append(part) continue if var_type == Routes._VAR_ANY_BREAK...
Yield URL parts. The given parts are usually in reverse order.
def make_params( key_parts: Sequence[str], variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]: # The unwrapped variable parts are in reverse order. # Instead of reversing those we reverse the key parts # and avoid the O(n) space required for reversing the vars r...
Map keys to variables. This map\ URL-pattern variables to\ a URL related parts :param key_parts: A list of URL parts :param variable_parts: A linked-list\ (ala nested tuples) of URL parts :return: The param dict with the values\ assigned to the keys :private:
def _deconstruct_url(self, url: str) -> List[str]: parts = url.split('/', self._max_depth + 1) if depth_of(parts) > self._max_depth: raise RouteError('No match') return parts
Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern :private:
def _match(self, parts: Sequence[str]) -> RouteResolved: route_match = None # type: RouteResolved route_variable_parts = tuple() # type: VariablePartsType # (route_partial, variable_parts, depth) to_visit = [(self._routes, tuple(), 0)] # type: List[Tuple[dict, tuple, int]] ...
Match URL parts to a registered pattern. This function is basically where all\ the CPU-heavy work is done. :param parts: URL parts :return: Matched route :raises kua.routes.RouteError: If there is no match :private:
def match(self, url: str) -> RouteResolved: url = normalize_url(url) parts = self._deconstruct_url(url) return self._match(parts)
Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no match
def add(self, url: str, anything: Any) -> None: url = normalize_url(url) parts = url.split('/') curr_partial_routes = self._routes curr_key_parts = [] for part in parts: if part.startswith(':*'): curr_key_parts.append(part[2:]) ...
Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the pattern for later\ retrieving. A dict with methods and callbacks,\ for example. Anything really. Registration order does not matter.\ Adding a URL firs...
def get_site_url(): site_url = getattr(_THREAD_LOCAL, _THREAD_SITE_URL, None) if site_url is None: site_url = SITE_URL or get_site_url_() setattr(_THREAD_LOCAL, _THREAD_SITE_URL, site_url) return site_url
Returns a URL for current site. :rtype: str|unicode
def get_message_type_for_app(app_name, default_message_type_alias): message_type = default_message_type_alias try: message_type = _MESSAGES_FOR_APPS[app_name][message_type] except KeyError: pass return get_registered_message_type(message_type)
Returns a registered message type object for a given application. Supposed to be used by reusable applications authors, to get message type objects which may be overridden by project authors using `override_message_type_for_app`. :param str|unicode app_name: :param str|unicode default_message_type...
def recipients(messenger, addresses): if isinstance(messenger, six.string_types): messenger = get_registered_messenger_object(messenger) return messenger._structure_recipients_data(addresses)
Structures recipients data. :param str|unicode, MessageBase messenger: MessengerBase heir :param list[str|unicode]|str|unicode addresses: recipients addresses or Django User model heir instances (NOTE: if supported by a messenger) :return: list of Recipient :rtype: list[Recipient]
def upcoming_live_chat(self): chat = None now = datetime.now() lcqs = self.get_query_set() lcqs = lcqs.filter( chat_ends_at__gte=now).order_by('-chat_starts_at') try: if settings.LIVECHAT_PRIMARY_CATEGORY: lcqs = lcqs.filter( ...
Find any upcoming or current live chat to advertise on the home page or live chat page. These are LiveChat's with primary category of 'ask-mama' and category of 'live-chat'. The Chat date must be less than 5 days away, or happening now.
def get_current_live_chat(self): now = datetime.now() chat = self.upcoming_live_chat() if chat and chat.is_in_progress(): return chat return None
Check if there is a live chat on the go, so that we should take over the AskMAMA page with the live chat.
def get_last_live_chat(self): now = datetime.now() lcqs = self.get_query_set() lcqs = lcqs.filter( chat_ends_at__lte=now, ).order_by('-chat_ends_at') for itm in lcqs: if itm.chat_ends_at + timedelta(days=3) > now: return itm ...
Check if there is a live chat that ended in the last 3 days, and return it. We will display a link to it on the articles page.
def comment_set(self): ct = ContentType.objects.get_for_model(self.__class__) qs = Comment.objects.filter( content_type=ct, object_pk=self.pk) qs = qs.exclude(is_removed=True) qs = qs.order_by('-submit_date') return qs
Get the comments that have been submitted for the chat
def _get_dispatches(filter_kwargs): dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).order_by('-message__time_created') return list(dispatches)
Simplified version. Not distributed friendly.
def _get_dispatches_for_update(filter_kwargs): dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).select_for_update( **GET_DISPATCHES_ARGS[1] ).order_by('-message__time_created') try: dispatches = list(dispatches) except NotSupported...
Distributed friendly version using ``select for update``.
def qs_valid(qs): ''' A filtering of the given Submission queryset for all submissions that were successfully validated. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of...
A filtering of the given Submission queryset for all submissions that were successfully validated. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full test status (not existent / fail...
def qs_tobegraded(qs): ''' A filtering of the given Submission queryset for all submissions that are gradeable. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full...
A filtering of the given Submission queryset for all submissions that are gradeable. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full test status (not existent / failed / success)....
def author_list(self): ''' The list of authors als text, for admin submission list overview.''' author_list = [self.submitter] + \ [author for author in self.authors.all().exclude(pk=self.submitter.pk)] return ",\n".join([author.get_full_name() for author in author_list]f author_list...
The list of authors als text, for admin submission list overview.
def grading_status_text(self): ''' A rendering of the grading that is an answer on the question "Is grading finished?". Used in duplicate view and submission list on the teacher backend. ''' if self.assignment.is_graded(): if self.is_grading_finished(): ...
A rendering of the grading that is an answer on the question "Is grading finished?". Used in duplicate view and submission list on the teacher backend.
def grading_value_text(self): ''' A rendering of the grading that is an answer to the question "What is the grade?". ''' if self.assignment.is_graded(): if self.is_grading_finished(): return str(self.grading) else: return st...
A rendering of the grading that is an answer to the question "What is the grade?".
def grading_means_passed(self): ''' Information if the given grading means passed. Non-graded assignments are always passed. ''' if self.assignment.is_graded(): if self.grading and self.grading.means_passed: return True else: ...
Information if the given grading means passed. Non-graded assignments are always passed.
def can_reupload(self, user=None): # Re-uploads are allowed only when test executions have failed. if self.state not in (self.TEST_VALIDITY_FAILED, self.TEST_FULL_FAILED): return False # It must be allowed to modify the submission. if not self.can_modify(user=user)...
Determines whether a submission can be re-uploaded. Returns a boolean value. Requires: can_modify. Re-uploads are allowed only when test executions have failed.
def get_initial_state(self): ''' Return first state for this submission after upload, which depends on the kind of assignment. ''' if not self.assignment.attachment_is_tested(): return Submission.SUBMITTED else: if self.assignment.attachmen...
Return first state for this submission after upload, which depends on the kind of assignment.
def get_chat_ids(self): updates = self.get_updates() chat_ids = [] if updates: for update in updates: message = update['message'] if message['text'] == '/start': chat_ids.append(message['chat']['id']) return list(se...
Returns unique chat IDs from `/start` command messages sent to our bot by users. Those chat IDs can be used to send messages to chats. :rtype: list
def _send_command(self, method_name, data=None): try: response = self.lib.post(self._tpl_url % {'token': self.auth_token, 'method': method_name}, data=data) json = response.json() if not json['ok']: raise TelegramMessengerException(json['description'...
Sends a command to API. :param str method_name: :param dict data: :return:
def get_queryset(self, request): ''' Restrict the listed submission files for the current user.''' qs = super(SubmissionFileAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(submissions__assignment__course__tutors_...
Restrict the listed submission files for the current user.
def register_builtin_message_types(): from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
Registers the built-in message types.
def view_links(obj): ''' Link to performance data and duplicate overview.''' result=format_html('') result+=format_html('<a href="%s" style="white-space: nowrap">Show duplicates</a><br/>'%reverse('duplicates', args=(obj.pk,))) result+=format_html('<a href="%s" style="white-space: nowrap">Show submission...
Link to performance data and duplicate overview.
def get_queryset(self, request): ''' Restrict the listed assignments for the current user.''' qs = super(AssignmentAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(course__active=True).filter(Q(course__tutors__pk=request.user.pk) | Q(course__owner=r...
Restrict the listed assignments for the current user.
def auth_complete(self, *args, **kwargs): if self.ENV_USERNAME in os.environ: response = os.environ elif type(self.strategy).__name__ == "DjangoStrategy" and self.ENV_USERNAME in self.strategy.request.META: # Looks like the Django strategy. In this case, it might by mod_...
Completes loging process, must return user instance
def get_user_details(self, response): result = { 'username': response[self.ENV_USERNAME], 'email': response.get(self.ENV_EMAIL, None), 'first_name': response.get(self.ENV_FIRST_NAME, None), 'last_name': response.get(self.ENV_LAST_NAME, None) } ...
Complete with additional information from environment, as available.
def file_link(self, instance): ''' Renders the link to the student upload file. ''' sfile = instance.file_upload if not sfile: return mark_safe('No file submitted by student.') else: return mark_safe('<a href="%s">%s</a><br/>(<a href="%s" targe...
Renders the link to the student upload file.
def get_queryset(self, request): ''' Restrict the listed submission for the current user.''' qs = super(SubmissionAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(assignment__course__tutors__pk=request.user.pk) | ...
Restrict the listed submission for the current user.
def formfield_for_dbfield(self, db_field, **kwargs): ''' Offer grading choices from the assignment definition as potential form field values for 'grading'. When no object is given in the form, the this is a new manual submission ''' if db_field.name == "grading": ...
Offer grading choices from the assignment definition as potential form field values for 'grading'. When no object is given in the form, the this is a new manual submission
def save_model(self, request, obj, form, change): ''' Our custom addition to the view adds an easy radio button choice for the new state. This is meant to be for tutors. We need to peel this choice from the form data and set the state accordingly. The radio buttons have no de...
Our custom addition to the view adds an easy radio button choice for the new state. This is meant to be for tutors. We need to peel this choice from the form data and set the state accordingly. The radio buttons have no default, so that we can keep the existing state if t...
def setGradingNotFinishedStateAction(self, request, queryset): ''' Set all marked submissions to "grading not finished". This is intended to support grading corrections on a larger scale. ''' for subm in queryset: subm.state = Submission.GRADING_IN_PROGRESS ...
Set all marked submissions to "grading not finished". This is intended to support grading corrections on a larger scale.
def setGradingFinishedStateAction(self, request, queryset): ''' Set all marked submissions to "grading finished". This is intended to support grading corrections on a larger scale. ''' for subm in queryset: subm.state = Submission.GRADED subm.save(...
Set all marked submissions to "grading finished". This is intended to support grading corrections on a larger scale.
def closeAndNotifyAction(self, request, queryset): ''' Close all submissions were the tutor sayed that the grading is finished, and inform the student. CLosing only graded submissions is a safeguard, since backend users tend to checkbox-mark all submissions without thinking. ''' ...
Close all submissions were the tutor sayed that the grading is finished, and inform the student. CLosing only graded submissions is a safeguard, since backend users tend to checkbox-mark all submissions without thinking.
def downloadArchiveAction(self, request, queryset): ''' Download selected submissions as archive, for targeted correction. ''' output = io.BytesIO() z = zipfile.ZipFile(output, 'w') for sub in queryset: sub.add_to_zipfile(z) z.close() # go ba...
Download selected submissions as archive, for targeted correction.
def directory_name_with_course(self): ''' The assignment name in a format that is suitable for a directory name. ''' coursename = self.course.directory_name() assignmentname = self.title.replace(" ", "_").replace("\\", "_").replace(",","").lower() return coursename + os.sep + assignment...
The assignment name in a format that is suitable for a directory name.
def grading_url(self): ''' Determines the teacher backend link to the filtered list of gradable submissions for this assignment. ''' grading_url="%s?coursefilter=%u&assignmentfilter=%u&statefilter=tobegraded"%( reverse('teacher:opensubmit_submission_change...
Determines the teacher backend link to the filtered list of gradable submissions for this assignment.
def has_perf_results(self): ''' Figure out if any submission for this assignment has performance data being available. ''' num_results = SubmissionTestResult.objects.filter(perf_data__isnull=False).filter(submission_file__submissions__assignment=self).count() return num_resul...
Figure out if any submission for this assignment has performance data being available.
def url(self, request): ''' Return absolute URL for assignment description. ''' if self.pk: if self.has_description(): return request.build_absolute_uri(reverse('assignment_description_file', args=[self.pk])) else: return self.d...
Return absolute URL for assignment description.
def duplicate_files(self): ''' Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this a...
Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this assignment
def download_and_run(config): ''' Main operation of the executor. Returns True when a job was downloaded and executed. Returns False when no job could be downloaded. ''' job = fetch_job(config) if job: job._run_validate() return True else: return Falsf download_a...
Main operation of the executor. Returns True when a job was downloaded and executed. Returns False when no job could be downloaded.
def copy_and_run(config, src_dir): ''' Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Ret...
Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Returns True when a job was prepared and executed....
def hashdict(d): k = 0 for key,val in d.items(): k ^= hash(key) ^ hash(val) return k
Hash a dictionary
def from_df(cls, df_long, df_short): pop = cls(1,1,1,1,1) #dummy population pop.orbpop_long = OrbitPopulation.from_df(df_long) pop.orbpop_short = OrbitPopulation.from_df(df_short) return pop
Builds TripleOrbitPopulation from DataFrame ``DataFrame`` objects must be of appropriate form to pass to :func:`OrbitPopulation.from_df`. :param df_long, df_short: :class:`pandas.DataFrame` objects to pass to :func:`OrbitPopulation.from_df`.
def load_hdf(cls, filename, path=''): df_long = pd.read_hdf(filename,'{}/long/df'.format(path)) df_short = pd.read_hdf(filename,'{}/short/df'.format(path)) return cls.from_df(df_long, df_short)
Load TripleOrbitPopulation from saved .h5 file. :param filename: HDF file name. :param path: Path within HDF file where data is stored.
def dRV(self,dt,com=False): if type(dt) != Quantity: dt *= u.day mean_motions = np.sqrt(G*(self.mred)*MSUN/(self.semimajor*AU)**3) mean_motions = np.sqrt(const.G*(self.mred)/(self.semimajor)**3) newM = self.M + mean_motions * dt pos,vel = orbit_posvel(newM,...
Change in RV of star 1 for time separation dt (default=days) :param dt: Time separation for which to compute RV change. If not a ``Quantity``, then assumed to be in days. :type dt: float, array-like, or ``Quantity`` :param com: (``bool``, optional) ...
def RV_timeseries(self,ts,recalc=False): if type(ts) != Quantity: ts *= u.day if not recalc and hasattr(self,'RV_measurements'): if (ts == self.ts).all(): return self._RV_measurements else: pass RVs = Quantity(np.zero...
Radial Velocity time series for star 1 at given times ts. :param ts: Times. If not ``Quantity``, assumed to be in days. :type ts: array-like or ``Quantity`` :param recalc: (optional) If ``False``, then if called with the exact same ``ts`` as las...
def from_df(cls, df): return cls(df['M1'], df['M2'], df['P'], ecc=df['ecc'], mean_anomaly=df['mean_anomaly'], obsx=df['obsx'], obsy=df['obsy'], obsz=df['obsz'])
Creates an OrbitPopulation from a DataFrame. :param df: :class:`pandas.DataFrame` object. Must contain the following columns: ``['M1','M2','P','ecc','mean_anomaly','obsx','obsy','obsz']``, i.e., as what is accessed via :attr:`OrbitPopulation.dataframe`. :return: ...
def load_hdf(cls, filename, path=''): df = pd.read_hdf(filename,'{}/df'.format(path)) return cls.from_df(df)
Loads OrbitPopulation from HDF file. :param filename: HDF file :param path: Path within HDF file store where :class:`OrbitPopulation` is saved.
def draw_pers_eccs(n,**kwargs): pers = draw_raghavan_periods(n) eccs = draw_eccs(n,pers,**kwargs) return pers,eccs
Draw random periods and eccentricities according to empirical survey data.
def draw_eccs(n,per=10,binsize=0.1,fuzz=0.05,maxecc=0.97): if np.size(per) == 1 or np.std(np.atleast_1d(per))==0: if np.size(per)>1: per = per[0] if per==0: es = np.zeros(n) else: ne=0 while ne<10: mask = np.absolute(np.log...
draws eccentricities appropriate to given periods, generated according to empirical data from Multiple Star Catalog
def withinroche(semimajors,M1,R1,M2,R2): q = M1/M2 return ((R1+R2)*RSUN) > (rochelobe(q)*semimajors*AU)
Returns boolean array that is True where two stars are within Roche lobe
def semimajor(P,mstar=1): return ((P*DAY/2/np.pi)**2*G*mstar*MSUN)**(1./3)/AU
Returns semimajor axis in AU given P in days, mstar in solar masses.
def fluxfrac(*mags): Ftot = 0 for mag in mags: Ftot += 10**(-0.4*mag) F1 = 10**(-0.4*mags[0]) return F1/Ftot
Returns fraction of total flux in first argument, assuming all are magnitudes.
def dfromdm(dm): if np.size(dm)>1: dm = np.atleast_1d(dm) return 10**(1+dm/5)
Returns distance given distance modulus.
def distancemodulus(d): if type(d)==Quantity: x = d.to('pc').value else: x = d #assumed to be pc if np.size(x)>1: d = np.atleast_1d(x) return 5*np.log10(x/10)
Returns distance modulus given d in parsec.
def split_path(path): parts = [] path, tail = os.path.split(path) while path and tail: parts.append(tail) path, tail = os.path.split(path) parts.append(os.path.join(path, tail)) return map(os.path.normpath, parts)[::-1]
"/tmp/test" Becomes: ("/", "tmp", "test")
def get_files(path): return_files = [] for root, dirs, files in os.walk(path): # Skip hidden files files = [f for f in files if not f[0] == '.'] dirs[:] = [d for d in dirs if not d[0] == '.'] for filename in files: return_files.append(os.path.join(root, filenam...
Returns a recursive list of all non-hidden files in and below the current directory.
def save_pkl(self, filename): with open(filename, 'wb') as fout: pickle.dump(self, fout)
Pickles TransitSignal.
def plot(self, fig=None, plot_trap=False, name=False, trap_color='g', trap_kwargs=None, **kwargs): setfig(fig) plt.plot(self.ts,self.fs,'.',**kwargs) if plot_trap and hasattr(self,'trapfit'): if trap_kwargs is None: trap_kwargs = {} ...
Makes a simple plot of signal :param fig: (optional) Argument for :func:`plotutils.setfig`. :param plot_trap: (optional) Whether to plot the (best-fit least-sq) trapezoid fit. :param name: (optional) Whether to annotate plot with the name of the signal; ...
def kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500, shortest=True,conftol=0.001,return_max=False): if xmin is None: xmin = kde.dataset.min() if xmax is None: xmax = kde.dataset.max() x = np.linspace(xmin,xmax,npts) return conf_interval(x,kde(x),shortest=shortest,con...
Returns desired confidence interval for provided KDE object
def qstd(x,quant=0.05,top=False,bottom=False): s = np.sort(x) n = np.size(x) lo = s[int(n*quant)] hi = s[int(n*(1-quant))] if top: w = np.where(x>=lo) elif bottom: w = np.where(x<=hi) else: w = np.where((x>=lo)&(x<=hi)) return np.std(x[w])
returns std, ignoring outer 'quant' pctiles
def conf_interval(x,L,conf=0.683,shortest=True, conftol=0.001,return_max=False): cum = np.cumsum(L) cdf = cum/cum.max() if shortest: maxind = L.argmax() if maxind==0: #hack alert maxind = 1 if maxind==len(L)-1: maxind = len(L)-2 ...
Returns desired 1-d confidence interval for provided x, L[PDF]
def add_units(self, units, factor, latexrepr=None): if units in self._units: raise ValueError('%s already defined' % units) if factor == 1: raise ValueError('Factor cannot be equal to 1') if latexrepr is None: latexrepr = units self._units[un...
Add new possible units. :arg units: units :type units: :class:`str` :arg factor: multiplication factor to convert new units into base units :type factor: :class:`float` :arg latexrepr: LaTeX representation of units (if ``None``, use *units) :ty...
def convert(self, value, units, newunits): return value * self._units[units] / self._units[newunits]
Converts a value expressed in certain *units* to a new units.
def setfig(fig=None,**kwargs): if fig: plt.figure(fig,**kwargs) plt.clf() elif fig==0: pass else: plt.figure(**kwargs)
Sets figure to 'fig' and clears; if fig is 0, does nothing (e.g. for overplotting) if fig is None (or anything else), creates new figure I use this for basically every function I write to make a plot. I give the function a "fig=None" kw argument, so that it will by default create a new figure. ...
def ldcoeffs(teff,logg=4.5,feh=0): teffs = np.atleast_1d(teff) loggs = np.atleast_1d(logg) Tmin,Tmax = (LDPOINTS[:,0].min(),LDPOINTS[:,0].max()) gmin,gmax = (LDPOINTS[:,1].min(),LDPOINTS[:,1].max()) teffs[(teffs < Tmin)] = Tmin + 1 teffs[(teffs > Tmax)] = Tmax - 1 loggs[(loggs < gmin)...
Returns limb-darkening coefficients in Kepler band.
def impact_parameter(a, R, inc, ecc=0, w=0, return_occ=False): b_tra = a*AU*np.cos(inc)/(R*RSUN) * (1-ecc**2)/(1 + ecc*np.sin(w)) if return_occ: b_tra = a*AU*np.cos(inc)/(R*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w)) return b_tra, b_occ else: return b_tra
a in AU, R in Rsun, inc & w in radians
def eclipse_depth(mafn,Rp,Rs,b,u1=0.394,u2=0.261,max_only=False,npts=100,force_1d=False): k = Rp*REARTH/(Rs*RSUN) if max_only: return 1 - mafn(k,b,u1,u2) if np.size(b) == 1: x = np.linspace(0,np.sqrt(1-b**2),npts) y = b zs = np.sqrt(x**2 + y**2) fs = mafn(k...
Calculates average (or max) eclipse depth ***why does b>1 take so freaking long?...
def minimum_inclination(P,M1,M2,R1,R2): P,M1,M2,R1,R2 = (np.atleast_1d(P), np.atleast_1d(M1), np.atleast_1d(M2), np.atleast_1d(R1), np.atleast_1d(R2)) semimajors = semimajor(P,M1+M2) rads = ((R1+R2)*RSUN/(semimajors*AU)...
Returns the minimum inclination at which two bodies from two given sets eclipse Only counts systems not within each other's Roche radius :param P: Orbital periods. :param M1,M2,R1,R2: Masses and radii of primary and secondary stars.
def a_over_Rs(P,R2,M2,M1=1,R1=1,planet=True): if planet: M2 *= REARTH/RSUN R2 *= MEARTH/MSUN return semimajor(P,M1+M2)*AU/(R1*RSUN)
Returns a/Rs for given parameters.
def eclipse_pars(P,M1,M2,R1,R2,ecc=0,inc=90,w=0,sec=False): a = semimajor(P,M1+M2) if sec: b = a*AU*np.cos(inc*np.pi/180)/(R1*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w*np.pi/180)) #aR = a*AU/(R2*RSUN) #I feel like this was to correct a bug, but this should not be. #p0 = R1/R2 #why this a...
retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w
def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True, cadence=1626./86400,frac=1,sec=False,pars0=None,tol=1e-4,width=3): ts,fs = eclipse(p0=p0,b=b,aR=aR,P=P,ecc=ecc,w=w,npts=npts,u1=u1,u2=u2, conv=conv,cadence=cadence,frac=frac,sec=sec,tol=tol,width=width...
Trapezoidal parameters for simulated orbit. All arguments passed to :func:`eclipse` except the following: :param pars0: (optional) Initial guess for least-sq optimization for trapezoid parameters. :return dur,dep,slope: Best-fit duration, depth, and T/tau for eclipse shape.
def fit_traptransit(ts,fs,p0): pfit,success = leastsq(traptransit_resid,p0,args=(ts,fs)) if success not in [1,2,3,4]: raise NoFitError #logging.debug('success = {}'.format(success)) return pfit
Fits trapezoid model to provided ts,fs
def traptransit_lhood(pars, ts, fs, sigs, maxslope=MAXSLOPE): if pars[0] < 0 or pars[1] < 0 or pars[2] < 2 or pars[2] > maxslope: return -np.inf fmod = traptransit(ts, pars) tot = 0 for i in range(len(ts)): tot += -0.5*(fmod[i] - fs[i])*(fmod[i] - fs[i]) / (sigs[i]*sigs[i]) ...
Params: depth, duration, slope, t0
def traptransit_MCMC(ts,fs,dfs=1e-5,nwalkers=200,nburn=300,niter=1000, threads=1,p0=[0.1,0.1,3,0],return_sampler=False, maxslope=MAXSLOPE): model = TraptransitModel(ts,fs,dfs,maxslope=maxslope) sampler = emcee.EnsembleSampler(nwalkers,4,model,threads=threads) T...
Fit trapezoidal model to provided ts, fs, [dfs] using MCMC. Standard emcee usage.
def backup(path, password_file=None): vault = VaultLib(get_vault_password(password_file)) with open(path, 'r') as f: encrypted_data = f.read() # Normally we'd just try and catch the exception, but the # exception raised here is not very specific (just # `AnsibleError`), so ...
Replaces the contents of a file with its decrypted counterpart, storing the original encrypted version and a hash of the file contents for later retrieval.
def restore(path, password_file=None): vault = VaultLib(get_vault_password(password_file)) atk_path = os.path.join(ATK_VAULT, path) # Load stored data with open(os.path.join(atk_path, 'encrypted'), 'rb') as f: old_data = f.read() with open(os.path.join(atk_path, 'hash'), 'rb') as f: ...
Retrieves a file from the atk vault and restores it to its original location, re-encrypting it if it has changed. :param path: path to original file