text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_live_chat(self): """ 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. """
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 return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment_set(self): """ Get the comments that have been submitted for the chat """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_dispatches(filter_kwargs): """Simplified version. Not distributed friendly."""
dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).order_by('-message__time_created') return list(dispatches)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_dispatches_for_update(filter_kwargs): """Distributed friendly version using ``select for update``."""
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 NotSupportedError: return None except DatabaseError: # Probably locked. That's fine. return [] return dispatches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(): return str('Yes ({0})'.format(self.grading)) else: return str('No') else: return str('Not graded')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 str('pending') else: if self.is_grading_finished(): return str('done') else: return str('not done')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_modify(self, user=None): """Determines whether the submission can be modified. Returns a boolean value. The 'user' parameter is optional and additionally checks whether the given user is authorized to perform these actions. This function checks the submission states and assignment deadlines."""
# The user must be authorized to commit these actions. if user and not self.user_can_modify(user): #self.log('DEBUG', "Submission cannot be modified, user is not an authorized user ({!r} not in {!r})", user, self.authorized_users) return False # Modification of submissions, that are withdrawn, graded or currently being graded, is prohibited. if self.state in [self.WITHDRAWN, self.GRADED, self.GRADING_IN_PROGRESS, ]: #self.log('DEBUG', "Submission cannot be modified, is in state '{}'", self.state) return False # Modification of closed submissions is prohibited. if self.is_closed(): if self.assignment.is_graded(): # There is a grading procedure, so taking it back would invalidate the tutors work #self.log('DEBUG', "Submission cannot be modified, it is closed and graded") return False else: #self.log('DEBUG', "Closed submission can be modified, since it has no grading scheme.") return True # Submissions, that are executed right now, cannot be modified if self.state in [self.TEST_VALIDITY_PENDING, self.TEST_FULL_PENDING]: if not self.file_upload: self.log( 'CRITICAL', "Submission is in invalid state! State is '{}', but there is no file uploaded!", self.state) raise AssertionError() return False if self.file_upload.is_executed(): # The above call informs that the uploaded file is being executed, or execution has been completed. # Since the current state is 'PENDING', the execution cannot yet be completed. # Thus, the submitted file is being executed right now. return False # Submissions must belong to an assignment. if not self.assignment: self.log('CRITICAL', "Submission does not belong to an assignment!") raise AssertionError() # Submissions, that belong to an assignment where the hard deadline has passed, # cannot be modified. if self.assignment.hard_deadline and timezone.now() > self.assignment.hard_deadline: #self.log('DEBUG', "Submission cannot be modified - assignment's hard deadline has passed (hard deadline is: {})", self.assignment.hard_deadline) return False # The soft deadline has no effect (yet). if self.assignment.soft_deadline: if timezone.now() > self.assignment.soft_deadline: # The soft deadline has passed pass # do nothing. #self.log('DEBUG', "Submission can be modified.") return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_reupload(self, user=None): """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."""
# 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): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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.attachment_test_validity: return Submission.TEST_VALIDITY_PENDING elif self.assignment.attachment_test_full: return Submission.TEST_FULL_PENDING
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def info_file(self, delete=True): ''' Prepares an open temporary file with information about the submission. Closing it will delete it, which must be considered by the caller. This file is not readable, since the tempfile library wants either readable or writable files. ''' info = tempfile.NamedTemporaryFile( mode='wt', encoding='utf-8', delete=delete) info.write("Submission ID:\t%u\n" % self.pk) info.write("Submitter:\t%s (%u)\n" % (self.submitter.get_full_name(), self.submitter.pk)) info.write("Authors:\n") for auth in self.authors.all(): info.write("\t%s (%u)\n" % (auth.get_full_name(), auth.pk)) info.write("\n") info.write("Creation:\t%s\n" % str(self.created)) info.write("Last modification:\t%s\n" % str(self.modified)) info.write("Status:\t%s\n" % self.state_for_students()) if self.grading: info.write("Grading:\t%s\n" % str(self.grading)) if self.notes: notes = self.notes info.write("Author notes:\n-------------\n%s\n\n" % notes) if self.grading_notes: notes = self.grading_notes info.write("Grading notes:\n--------------\n%s\n\n" % notes) info.flush() # no closing here, because it disappears then return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy_file_upload(self, targetdir): ''' Copies the currently valid file upload into the given directory. If possible, the content is un-archived in the target directory. ''' assert(self.file_upload) # unpack student data to temporary directory # os.chroot is not working with tarfile support tempdir = tempfile.mkdtemp() try: if zipfile.is_zipfile(self.file_upload.absolute_path()): f = zipfile.ZipFile(self.file_upload.absolute_path(), 'r') f.extractall(targetdir) elif tarfile.is_tarfile(self.file_upload.absolute_path()): tar = tarfile.open(self.file_upload.absolute_path()) tar.extractall(targetdir) tar.close() else: # unpacking not possible, just copy it shutil.copyfile(self.file_upload.absolute_path(), targetdir + "/" + self.file_upload.basename()) except IOError: logger.error("I/O exception while accessing %s." % (self.file_upload.absolute_path())) pass except (UnicodeEncodeError, NotImplementedError) as e: # unpacking not possible, just copy it shutil.copyfile(self.file_upload.absolute_path(), targetdir + "/" + self.file_upload.basename()) pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_command(self, method_name, data=None): """Sends a command to API. :param str method_name: :param dict data: :return: """
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']) return json['result'] except self.lib.exceptions.RequestException as e: raise TelegramMessengerException(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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__pk=request.user.pk) | Q(submissions__assignment__course__owner=request.user)).distinct()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_builtin_message_types(): """Registers the built-in message types."""
from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 submissions</a><br/>'%obj.grading_url()) result+=format_html('<a href="%s" style="white-space: nowrap">Download submissions</a>'%reverse('assarchive', args=(obj.pk,))) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clean(self): ''' Check if such an assignment configuration makes sense, and reject it otherwise. This mainly relates to interdependencies between the different fields, since single field constraints are already clatified by the Django model configuration. ''' super(AssignmentAdminForm, self).clean() d = defaultdict(lambda: False) d.update(self.cleaned_data) # Having validation or full test enabled demands file upload if d['attachment_test_validity'] and not d['has_attachment']: raise ValidationError('You cannot have a validation script without allowing file upload.') if d['attachment_test_full'] and not d['has_attachment']: raise ValidationError('You cannot have a full test script without allowing file upload.') # Having validation or full test enabled demands a test machine if d['attachment_test_validity'] and 'test_machines' in d and not len(d['test_machines'])>0: raise ValidationError('You cannot have a validation script without specifying test machines.') if d['attachment_test_full'] and 'test_machines' in d and not len(d['test_machines'])>0: raise ValidationError('You cannot have a full test script without specifying test machines.') if d['download'] and d['description']: raise ValidationError('You can only have a description link OR a description file.') if not d['download'] and not d['description']: raise ValidationError('You need a description link OR a description file.') # Having test machines demands compilation or validation scripts if 'test_machines' in d and len(d['test_machines'])>0 \ and not 'attachment_test_validity' in d \ and not 'attachment_test_full' in d: raise ValidationError('For using test machines, you need to enable validation or full test.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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=request.user)).distinct() return qs.order_by('title')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_details(self, response): """ Complete with additional information from environment, as available. """
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) } if result['first_name'] and result['last_name']: result['fullname']=result['first_name']+' '+result['last_name'] logger.debug("Returning user details: "+str(result)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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" target="_new">Preview</a>)' % (sfile.get_absolute_url(), sfile.basename(), sfile.get_preview_url()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) | Q(assignment__course__owner=request.user)).distinct()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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": submurl = kwargs['request'].path try: # Does not work on new submission action by admin or with a change of URLs. The former is expectable. submid = [int(s) for s in submurl.split('/') if s.isdigit()][0] kwargs["queryset"] = Submission.objects.get( pk=submid).assignment.gradingScheme.gradings except: kwargs["queryset"] = Grading.objects.none() return super(SubmissionAdmin, self).formfield_for_dbfield(db_field, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 default, so that we can keep the existing state if the user makes no explicit choice. Everything else can be managed as prepared by the framework. ''' if 'newstate' in request.POST: if request.POST['newstate'] == 'finished': obj.state = Submission.GRADED elif request.POST['newstate'] == 'unfinished': obj.state = Submission.GRADING_IN_PROGRESS obj.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 subm.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' mails = [] qs = queryset.filter(Q(state=Submission.GRADED)) for subm in qs: subm.inform_student(request, Submission.CLOSED) mails.append(str(subm.pk)) # works in bulk because inform_student never fails qs.update(state=Submission.CLOSED) if len(mails) == 0: self.message_user(request, "Nothing closed, no mails sent.") else: self.message_user( request, "Mail sent for submissions: " + ",".join(mails))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 back to start in ZIP file so that Django can deliver it output.seek(0) response = HttpResponse( output, content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename=submissions.zip' return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 + assignmentname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_changelist'), self.course.pk, self.pk ) return grading_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_results != 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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.download else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def can_create_submission(self, user=None): ''' Central access control for submitting things related to assignments. ''' if user: # Super users, course owners and tutors should be able to test their validations # before the submission is officially possible. # They should also be able to submit after the deadline. if user.is_superuser or user is self.course.owner or self.course.tutors.filter(pk=user.pk).exists(): return True if self.course not in user.profile.user_courses(): # The user is not enrolled in this assignment's course. logger.debug('Submission not possible, user not enrolled in the course.') return False if user.authored.filter(assignment=self).exclude(state=Submission.WITHDRAWN).count() > 0: # User already has a valid submission for this assignment. logger.debug('Submission not possible, user already has one for this assignment.') return False if self.hard_deadline and self.hard_deadline < timezone.now(): # Hard deadline has been reached. logger.debug('Submission not possible, hard deadline passed.') return False if self.publish_at > timezone.now() and not user.profile.can_see_future(): # The assignment has not yet been published. logger.debug('Submission not possible, assignment has not yet been published.') return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> 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 assignment ''' result=list() files = SubmissionFile.valid_ones.order_by('md5') for key, dup_group in groupby(files, lambda f: f.md5): file_list=[entry for entry in dup_group] if len(file_list)>1: for entry in file_list: if entry.submissions.filter(assignment=self).count()>0: result.append([key, file_list]) break return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 Returns True when a job was prepared and executed. Returns False when no job could be prepared. ''' job = fake_fetch_job(config, src_dir) if job: job._run_validate() return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def console_script(): ''' The main entry point for the production administration script 'opensubmit-exec', installed by setuptools. ''' if len(sys.argv) == 1: print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]") return 0 if "help" in sys.argv[1]: print("configcreate <server_url>: Create initial config file for the OpenSubmit executor.") print("configtest: Check config file for correct installation of the OpenSubmit executor.") print("run: Fetch and run code to be tested from the OpenSubmit web server. Suitable for crontab.") print("test <dir>: Run test script from a local folder for testing purposes.") print("unlock: Break the script lock, because of crashed script.") print("help: Print this help") print( "-c config_file Configuration file to be used (default: {0})".format(CONFIG_FILE_DEFAULT)) return 0 # Translate legacy commands if sys.argv[1] == "configure": sys.argv[1] = 'configtest' config_fname = get_config_fname(sys.argv) if "configcreate" in sys.argv[1]: print("Creating config file at " + config_fname) server_url = sys.argv[2] if create_config(config_fname, override_url=server_url): print("Config file created, fetching jobs from " + server_url) return 0 else: return 1 if "configtest" in sys.argv[1]: print("Testing config file at " + config_fname) if has_config(config_fname): config = read_config(config_fname) if not check_config(config): return 1 else: print("ERROR: Seems like the config file %s does not exist. Call 'opensubmit-exec configcreate <server_url>' first." % config_fname) return 1 print("Sending host information update to server ...") send_hostinfo(config) return 0 if "unlock" in sys.argv[1]: config = read_config(config_fname) break_lock(config) return 0 if "run" in sys.argv[1]: config = read_config(config_fname) # Perform additional precautions for unattended mode in cron kill_longrunning(config) with ScriptLock(config): download_and_run(config) return 0 if "test" in sys.argv[1]: config = read_config(config_fname) copy_and_run(config, sys.argv[2]) return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hashdict(d): """Hash a dictionary """
k = 0 for key,val in d.items(): k ^= hash(key) ^ hash(val) return k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_df(cls, df_long, df_short): """ 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`. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_hdf(cls, filename, path=''): """ Load TripleOrbitPopulation from saved .h5 file. :param filename: HDF file name. :param path: Path within HDF file where data is stored. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RV_timeseries(self,ts,recalc=False): """ 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 last call, it will return cached calculation. """
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.zeros((len(ts),self.N)),unit='km/s') for i,t in enumerate(ts): RVs[i,:] = self.dRV(t,com=True) self._RV_measurements = RVs self.ts = ts return RVs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_df(cls, df): """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: :class:`OrbitPopulation`. """
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'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_hdf(cls, filename, path=''): """Loads OrbitPopulation from HDF file. :param filename: HDF file :param path: Path within HDF file store where :class:`OrbitPopulation` is saved. """
df = pd.read_hdf(filename,'{}/df'.format(path)) return cls.from_df(df)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_pers_eccs(n,**kwargs): """ Draw random periods and eccentricities according to empirical survey data. """
pers = draw_raghavan_periods(n) eccs = draw_eccs(n,pers,**kwargs) return pers,eccs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_eccs(n,per=10,binsize=0.1,fuzz=0.05,maxecc=0.97): """draws eccentricities appropriate to given periods, generated according to empirical data from Multiple Star Catalog """
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.log10(MSC_TRIPLEPERS)-np.log10(per))<binsize/2. es = MSC_TRIPDATA.e[mask] ne = len(es) if ne<10: binsize*=1.1 inds = rand.randint(ne,size=n) es = es[inds] * (1 + rand.normal(size=n)*fuzz) else: longmask = (per > 25) shortmask = (per <= 25) es = np.zeros(np.size(per)) elongs = MSC_TRIPDATA.e[MSC_TRIPLEPERS > 25] eshorts = MSC_TRIPDATA.e[MSC_TRIPLEPERS <= 25] n = np.size(per) nlong = longmask.sum() nshort = shortmask.sum() nelongs = np.size(elongs) neshorts = np.size(eshorts) ilongs = rand.randint(nelongs,size=nlong) ishorts = rand.randint(neshorts,size=nshort) es[longmask] = elongs[ilongs] es[shortmask] = eshorts[ishorts] es = es * (1 + rand.normal(size=n)*fuzz) es[es>maxecc] = maxecc return np.absolute(es)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def withinroche(semimajors,M1,R1,M2,R2): """ Returns boolean array that is True where two stars are within Roche lobe """
q = M1/M2 return ((R1+R2)*RSUN) > (rochelobe(q)*semimajors*AU)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def semimajor(P,mstar=1): """Returns semimajor axis in AU given P in days, mstar in solar masses. """
return ((P*DAY/2/np.pi)**2*G*mstar*MSUN)**(1./3)/AU
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fluxfrac(*mags): """Returns fraction of total flux in first argument, assuming all are magnitudes. """
Ftot = 0 for mag in mags: Ftot += 10**(-0.4*mag) F1 = 10**(-0.4*mags[0]) return F1/Ftot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfromdm(dm): """Returns distance given distance modulus. """
if np.size(dm)>1: dm = np.atleast_1d(dm) return 10**(1+dm/5)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distancemodulus(d): """Returns distance modulus given d in parsec. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_files(path): """ Returns a recursive list of all non-hidden files in and below the current directory. """
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, filename)) return return_files
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_pkl(self, filename): """ Pickles TransitSignal. """
with open(filename, 'wb') as fout: pickle.dump(self, fout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, fig=None, plot_trap=False, name=False, trap_color='g', trap_kwargs=None, **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; can be ``True`` (in which case ``self.name`` will be used), or any arbitrary string. :param trap_color: (optional) Color of trapezoid fit line. :param trap_kwargs: (optional) Keyword arguments to pass to trapezoid fit line. :param **kwargs: (optional) Additional keyword arguments passed to ``plt.plot``. """
setfig(fig) plt.plot(self.ts,self.fs,'.',**kwargs) if plot_trap and hasattr(self,'trapfit'): if trap_kwargs is None: trap_kwargs = {} plt.plot(self.ts, traptransit(self.ts,self.trapfit), color=trap_color, **trap_kwargs) if name is not None: if type(name)==type(''): text = name else: text = self.name plt.annotate(text,xy=(0.1,0.1),xycoords='axes fraction',fontsize=22) if hasattr(self,'depthfit') and not np.isnan(self.depthfit[0]): lo = 1 - 3*self.depthfit[0] hi = 1 + 2*self.depthfit[0] else: lo = 1 hi = 1 sig = qstd(self.fs,0.005) hi = max(hi,self.fs.mean() + 7*sig) lo = min(lo,self.fs.mean() - 7*sig) logging.debug('lo={}, hi={}'.format(lo,hi)) plt.ylim((lo,hi)) plt.xlabel('time [days]') plt.ylabel('Relative flux')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500, shortest=True,conftol=0.001,return_max=False): """ Returns desired confidence interval for provided KDE object """
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,conf=conf, conftol=conftol,return_max=return_max)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qstd(x,quant=0.05,top=False,bottom=False): """returns std, ignoring outer 'quant' pctiles """
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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot2dhist(xdata,ydata,cmap='binary',interpolation='nearest', fig=None,logscale=True,xbins=None,ybins=None, nbins=50,pts_only=False,**kwargs): """Plots a 2d density histogram of provided data :param xdata,ydata: (array-like) Data to plot. :param cmap: (optional) Colormap to use for density plot. :param interpolation: (optional) Interpolation scheme for display (passed to ``plt.imshow``). :param fig: (optional) Argument passed to :func:`setfig`. :param logscale: (optional) If ``True`` then the colormap will be based on a logarithmic scale, rather than linear. :param xbins,ybins: (optional) Bin edges to use (if ``None``, then use ``np.histogram2d`` to find bins automatically). :param nbins: (optional) Number of bins to use (if ``None``, then use ``np.histogram2d`` to find bins automatically). :param pts_only: (optional) If ``True``, then just a scatter plot of the points is made, rather than the density plot. :param **kwargs: Keyword arguments passed either to ``plt.plot`` or ``plt.imshow`` depending upon whether ``pts_only`` is set to ``True`` or not. """
setfig(fig) if pts_only: plt.plot(xdata,ydata,**kwargs) return ok = (~np.isnan(xdata) & ~np.isnan(ydata) & ~np.isinf(xdata) & ~np.isinf(ydata)) if ~ok.sum() > 0: logging.warning('{} x values and {} y values are nan'.format(np.isnan(xdata).sum(), np.isnan(ydata).sum())) logging.warning('{} x values and {} y values are inf'.format(np.isinf(xdata).sum(), np.isinf(ydata).sum())) if xbins is not None and ybins is not None: H,xs,ys = np.histogram2d(xdata[ok],ydata[ok],bins=(xbins,ybins)) else: H,xs,ys = np.histogram2d(xdata[ok],ydata[ok],bins=nbins) H = H.T if logscale: H = np.log(H) extent = [xs[0],xs[-1],ys[0],ys[-1]] plt.imshow(H,extent=extent,interpolation=interpolation, aspect='auto',cmap=cmap,origin='lower',**kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ldcoeffs(teff,logg=4.5,feh=0): """ Returns limb-darkening coefficients in Kepler band. """
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)] = gmin + 0.01 loggs[(loggs > gmax)] = gmax - 0.01 u1,u2 = (U1FN(teffs,loggs),U2FN(teffs,loggs)) return u1,u2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def impact_parameter(a, R, inc, ecc=0, w=0, return_occ=False): """a in AU, R in Rsun, inc & w in radians """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum_inclination(P,M1,M2,R1,R2): """ 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. """
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)) ok = (~np.isnan(rads) & ~withinroche(semimajors,M1,R1,M2,R2)) if ok.sum() == 0: logging.error('P: {}'.format(P)) logging.error('M1: {}'.format(M1)) logging.error('M2: {}'.format(M2)) logging.error('R1: {}'.format(R1)) logging.error('R2: {}'.format(R2)) if np.all(withinroche(semimajors,M1,R1,M2,R2)): raise AllWithinRocheError('All simulated systems within Roche lobe') else: raise EmptyPopulationError('no valid systems! (see above)') mininc = np.arccos(rads[ok].max())*180/np.pi return mininc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eclipse_pars(P,M1,M2,R1,R2,ecc=0,inc=90,w=0,sec=False): """retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w"""
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 also? else: 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/(R1*RSUN) #p0 = R2/R1 p0 = R2/R1 aR = a*AU/(R1*RSUN) return p0,b,aR
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit_traptransit(ts,fs,p0): """ Fits trapezoid model to provided ts,fs """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backup(path, password_file=None): """ 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. """
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 this feels safer to avoid suppressing # other things that might go wrong. if vault.is_encrypted(encrypted_data): decrypted_data = vault.decrypt(encrypted_data) # Create atk vault files atk_path = os.path.join(ATK_VAULT, path) mkdir_p(atk_path) # ... encrypted with open(os.path.join(atk_path, 'encrypted'), 'wb') as f: f.write(encrypted_data) # ... hash with open(os.path.join(atk_path, 'hash'), 'wb') as f: f.write(hashlib.sha1(decrypted_data).hexdigest()) # Replace encrypted file with decrypted one with open(path, 'wb') as f: f.write(decrypted_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(path, password_file=None): """ 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 """
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: old_hash = f.read() # Load new data with open(path, 'rb') as f: new_data = f.read() new_hash = hashlib.sha1(new_data).hexdigest() # Determine whether to re-encrypt if old_hash != new_hash: new_data = vault.encrypt(new_data) else: new_data = old_data # Update file with open(path, 'wb') as f: f.write(new_data) # Clean atk vault os.remove(os.path.join(atk_path, 'encrypted')) os.remove(os.path.join(atk_path, 'hash'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, other): """Appends stars from another StarPopulations, in place. :param other: Another :class:`StarPopulation`; must have same columns as ``self``. """
if not isinstance(other,StarPopulation): raise TypeError('Only StarPopulation objects can be appended to a StarPopulation.') if not np.all(self.stars.columns == other.stars.columns): raise ValueError('Two populations must have same columns to combine them.') if len(self.constraints) > 0: logging.warning('All constraints are cleared when appending another population.') self.stars = pd.concat((self.stars, other.stars)) if self.orbpop is not None and other.orbpop is not None: self.orbpop = self.orbpop + other.orbpop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bands(self): """ Bandpasses for which StarPopulation has magnitude data """
bands = [] for c in self.stars.columns: if re.search('_mag',c): bands.append(c) return bands
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(self,value): """New distance value must be a ``Quantity`` object """
self.stars['distance'] = value.to('pc').value old_distmod = self.stars['distmod'].copy() new_distmod = distancemodulus(self.stars['distance']) for m in self.bands: self.stars[m] += new_distmod - old_distmod self.stars['distmod'] = new_distmod logging.warning('Setting the distance manually may have screwed up your constraints. Re-apply constraints as necessary.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distok(self): """ Boolean array showing which stars pass all distribution constraints. A "distribution constraint" is a constraint that affects the distribution of stars, rather than just the number. """
ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name] if c.name not in self.distribution_skip: ok &= c.ok return ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def countok(self): """ Boolean array showing which stars pass all count constraints. A "count constraint" is a constraint that affects the number of stars. """
ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name] if c.name not in self.selectfrac_skip: ok &= c.ok return ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prophist2d(self,propx,propy, mask=None, logx=False,logy=False, fig=None,selected=False,**kwargs): """Makes a 2d density histogram of two given properties :param propx,propy: Names of properties to histogram. Must be names of columns in ``self.stars`` table. :param mask: (optional) Boolean mask (``True`` is good) to say which indices to plot. Must be same length as ``self.stars``. :param logx,logy: (optional) Whether to plot the log10 of x and/or y properties. :param fig: (optional) Argument passed to :func:`plotutils.setfig`. :param selected: (optional) If ``True``, then only the "selected" stars (that is, stars obeying all distribution constraints attached to this object) will be plotted. In this case, ``mask`` will be ignored. :param kwargs: Additional keyword arguments passed to :func:`plotutils.plot2dhist`. """
if mask is not None: inds = np.where(mask)[0] else: if selected: inds = self.selected.index else: inds = self.stars.index if selected: xvals = self.selected[propx].iloc[inds].values yvals = self.selected[propy].iloc[inds].values else: if mask is None: mask = np.ones_like(self.stars.index) xvals = self.stars[mask][propx].values yvals = self.stars[mask][propy].values #forward-hack for EclipsePopulations... #TODO: reorganize. if propx=='depth' and hasattr(self,'depth'): xvals = self.depth.iloc[inds].values if propy=='depth' and hasattr(self,'depth'): yvals = self.depth.iloc[inds].values if logx: xvals = np.log10(xvals) if logy: yvals = np.log10(yvals) plot2dhist(xvals,yvals,fig=fig,**kwargs) plt.xlabel(propx) plt.ylabel(propy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prophist(self,prop,fig=None,log=False, mask=None, selected=False,**kwargs): """Plots a 1-d histogram of desired property. :param prop: Name of property to plot. Must be column of ``self.stars``. :param fig: (optional) Argument for :func:`plotutils.setfig` :param log: (optional) Whether to plot the histogram of log10 of the property. :param mask: (optional) Boolean array (length of ``self.stars``) to say which indices to plot (``True`` is good). :param selected: (optional) If ``True``, then only the "selected" stars (that is, stars obeying all distribution constraints attached to this object) will be plotted. In this case, ``mask`` will be ignored. :param **kwargs: Additional keyword arguments passed to :func:`plt.hist`. """
setfig(fig) inds = None if mask is not None: inds = np.where(mask)[0] elif inds is None: if selected: #inds = np.arange(len(self.selected)) inds = self.selected.index else: #inds = np.arange(len(self.stars)) inds = self.stars.index if selected: vals = self.selected[prop].values#.iloc[inds] #invalidates mask? else: vals = self.stars[prop].iloc[inds].values if prop=='depth' and hasattr(self,'depth'): vals *= self.dilution_factor[inds] if log: h = plt.hist(np.log10(vals),**kwargs) else: h = plt.hist(vals,**kwargs) plt.xlabel(prop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraint_stats(self,primarylist=None): """Returns information about effect of constraints on population. :param primarylist: List of constraint names that you want specific information on (i.e., not blended within "multiple constraints".) :return: ``dict`` of what percentage of population is ruled out by each constraint, including a "multiple constraints" entry. """
if primarylist is None: primarylist = [] n = len(self.stars) primaryOK = np.ones(n).astype(bool) tot_reject = np.zeros(n) for name in self.constraints: if name in self.selectfrac_skip: continue c = self.constraints[name] if name in primarylist: primaryOK &= c.ok tot_reject += ~c.ok primary_rejected = ~primaryOK secondary_rejected = tot_reject - primary_rejected lone_reject = {} for name in self.constraints: if name in primarylist or name in self.selectfrac_skip: continue c = self.constraints[name] lone_reject[name] = ((secondary_rejected==1) & (~primary_rejected) & (~c.ok)).sum()/float(n) mult_rejected = (secondary_rejected > 1) & (~primary_rejected) not_rejected = ~(tot_reject.astype(bool)) primary_reject_pct = primary_rejected.sum()/float(n) mult_reject_pct = mult_rejected.sum()/float(n) not_reject_pct = not_rejected.sum()/float(n) tot = 0 results = {} results['pri'] = primary_reject_pct tot += primary_reject_pct for name in lone_reject: results[name] = lone_reject[name] tot += lone_reject[name] results['multiple constraints'] = mult_reject_pct tot += mult_reject_pct results['remaining'] = not_reject_pct tot += not_reject_pct if tot != 1: logging.warning('total adds up to: %.2f (%s)' % (tot,self.model)) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraint_piechart(self,primarylist=None, fig=None,title='',colordict=None, legend=True,nolabels=False): """Makes piechart illustrating constraints on population :param primarylist: (optional) List of most import constraints to show (see :func:`StarPopulation.constraint_stats`) :param fig: (optional) Passed to :func:`plotutils.setfig`. :param title: (optional) Title for pie chart :param colordict: (optional) Dictionary describing colors (keys are constraint names). :param legend: (optional) ``bool`` indicating whether to display a legend. :param nolabels: (optional) If ``True``, then leave out legend labels. """
setfig(fig,figsize=(6,6)) stats = self.constraint_stats(primarylist=primarylist) if primarylist is None: primarylist = [] if len(primarylist)==1: primaryname = primarylist[0] else: primaryname = '' for name in primarylist: primaryname += '%s,' % name primaryname = primaryname[:-1] fracs = [] labels = [] explode = [] colors = [] fracs.append(stats['remaining']*100) labels.append('remaining') explode.append(0.05) colors.append('b') if 'pri' in stats and stats['pri']>=0.005: fracs.append(stats['pri']*100) labels.append(primaryname) explode.append(0) if colordict is not None: colors.append(colordict[primaryname]) for name in stats: if name == 'pri' or \ name == 'multiple constraints' or \ name == 'remaining': continue fracs.append(stats[name]*100) labels.append(name) explode.append(0) if colordict is not None: colors.append(colordict[name]) if stats['multiple constraints'] >= 0.005: fracs.append(stats['multiple constraints']*100) labels.append('multiple constraints') explode.append(0) colors.append('w') autopct = '%1.1f%%' if nolabels: labels = None if legend: legendlabels = [] for i,l in enumerate(labels): legendlabels.append('%s (%.1f%%)' % (l,fracs[i])) labels = None autopct = '' if colordict is None: plt.pie(fracs,labels=labels,autopct=autopct,explode=explode) else: plt.pie(fracs,labels=labels,autopct=autopct,explode=explode, colors=colors) if legend: plt.legend(legendlabels,bbox_to_anchor=(-0.05,0), loc='lower left',prop={'size':10}) plt.title(title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraints(self): """ Constraints applied to the population. """
try: return self._constraints except AttributeError: self._constraints = ConstraintDict() return self._constraints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hidden_constraints(self): """ Constraints applied to the population, but temporarily removed. """
try: return self._hidden_constraints except AttributeError: self._hidden_constraints = ConstraintDict() return self._hidden_constraints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_constraint(self,constraint,selectfrac_skip=False, distribution_skip=False,overwrite=False): """Apply a constraint to the population :param constraint: Constraint to apply. :type constraint: :class:`Constraint` :param selectfrac_skip: (optional) If ``True``, then this constraint will not be considered towards diminishing the """
#grab properties constraints = self.constraints my_selectfrac_skip = self.selectfrac_skip my_distribution_skip = self.distribution_skip if constraint.name in constraints and not overwrite: logging.warning('constraint already applied: {}'.format(constraint.name)) return constraints[constraint.name] = constraint if selectfrac_skip: my_selectfrac_skip.append(constraint.name) if distribution_skip: my_distribution_skip.append(constraint.name) #forward-looking for EclipsePopulation if hasattr(self, '_make_kde'): self._make_kde() self.constraints = constraints self.selectfrac_skip = my_selectfrac_skip self.distribution_skip = my_distribution_skip
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_constraint(self,name,selectfrac_skip=False,distribution_skip=False): """ Re-apply constraint that had been removed :param name: Name of constraint to replace :param selectfrac_skip,distribution_skip: (optional) Same as :func:`StarPopulation.apply_constraint` """
hidden_constraints = self.hidden_constraints if name in hidden_constraints: c = hidden_constraints[name] self.apply_constraint(c,selectfrac_skip=selectfrac_skip, distribution_skip=distribution_skip) del hidden_constraints[name] else: logging.warning('Constraint {} not available for replacement.'.format(name)) self.hidden_constraints = hidden_constraints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constrain_property(self,prop,lo=-np.inf,hi=np.inf, measurement=None,thresh=3, selectfrac_skip=False,distribution_skip=False): """Apply constraint that constrains property. :param prop: Name of property. Must be column in ``self.stars``. :type prop: ``str`` :param lo,hi: (optional) Low and high allowed values for ``prop``. Defaults to ``-np.inf`` and ``np.inf`` to allow for defining only lower or upper limits if desired. :param measurement: (optional) Value and error of measurement in form ``(value, error)``. :param thresh: (optional) Number of "sigma" to allow for measurement constraint. :param selectfrac_skip,distribution_skip: Passed to :func:`StarPopulation.apply_constraint`. """
if prop in self.constraints: logging.info('re-doing {} constraint'.format(prop)) self.remove_constraint(prop) if measurement is not None: val,dval = measurement self.apply_constraint(MeasurementConstraint(getattr(self.stars,prop), val,dval,name=prop, thresh=thresh), selectfrac_skip=selectfrac_skip, distribution_skip=distribution_skip) else: self.apply_constraint(RangeConstraint(getattr(self.stars,prop), lo=lo,hi=hi,name=prop), selectfrac_skip=selectfrac_skip, distribution_skip=distribution_skip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_trend_constraint(self, limit, dt, distribution_skip=False, **kwargs): """ Constrains change in RV to be less than limit over time dt. Only works if ``dRV`` and ``Plong`` attributes are defined for population. :param limit: Radial velocity limit on trend. Must be :class:`astropy.units.Quantity` object, or else interpreted as m/s. :param dt: Time baseline of RV observations. Must be :class:`astropy.units.Quantity` object; else interpreted as days. :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* :param **kwargs: Additional keyword arguments passed to :func:`StarPopulation.apply_constraint`. """
if type(limit) != Quantity: limit = limit * u.m/u.s if type(dt) != Quantity: dt = dt * u.day dRVs = np.absolute(self.dRV(dt)) c1 = UpperLimit(dRVs, limit) c2 = LowerLimit(self.Plong, dt*4) self.apply_constraint(JointConstraintOr(c1,c2,name='RV monitoring', Ps=self.Plong,dRVs=dRVs), distribution_skip=distribution_skip, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_cc(self, cc, distribution_skip=False, **kwargs): """ Apply contrast-curve constraint to population. Only works if object has ``Rsky``, ``dmag`` attributes :param cc: Contrast curve. :type cc: :class:`ContrastCurveConstraint` :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* :param **kwargs: Additional keyword arguments passed to :func:`StarPopulation.apply_constraint`. """
rs = self.Rsky.to('arcsec').value dmags = self.dmag(cc.band) self.apply_constraint(ContrastCurveConstraint(rs,dmags,cc,name=cc.name), distribution_skip=distribution_skip, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_vcc(self, vcc, distribution_skip=False, **kwargs): """ Applies "velocity contrast curve" to population. That is, the constraint that comes from not seeing two sets of spectral lines in a high resolution spectrum. Only works if population has ``dmag`` and ``RV`` attributes. :param vcc: Velocity contrast curve; dmag vs. delta-RV. :type cc: :class:`VelocityContrastCurveConstraint` :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* :param **kwargs: Additional keyword arguments passed to :func:`StarPopulation.apply_constraint`. """
rvs = self.RV.value dmags = self.dmag(vcc.band) self.apply_constraint(VelocityContrastCurveConstraint(rvs,dmags,vcc, name='secondary spectrum'), distribution_skip=distribution_skip, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_maxrad(self,maxrad, distribution_skip=True): """ Adds a constraint that rejects everything with Rsky > maxrad Requires ``Rsky`` attribute, which should always have units. :param maxrad: The maximum angular value of Rsky. :type maxrad: :class:`astropy.units.Quantity` :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* """
self.maxrad = maxrad self.apply_constraint(UpperLimit(self.Rsky,maxrad, name='Max Rsky'), overwrite=True, distribution_skip=distribution_skip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraint_df(self): """ A DataFrame representing all constraints, hidden or not """
df = pd.DataFrame() for name,c in self.constraints.items(): df[name] = c.ok for name,c in self.hidden_constraints.items(): df[name] = c.ok return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_hdf(self,filename,path='',properties=None, overwrite=False, append=False): """Saves to HDF5 file. Subclasses should be sure to define ``_properties`` attribute to ensure that all correct attributes get saved. Load a saved population with :func:`StarPopulation.load_hdf`. Example usage:: True True :param filename: Name of HDF file. :param path: (optional) Path within HDF file to save object. :param properties: (optional) Names of any properties (in addition to those defined in ``_properties`` attribute) that you wish to save. (This is an old keyword, and should probably be removed. Feel free to ignore it.) :param overwrite: (optional) Whether to overwrite file if it already exists. If ``True``, then any existing file will be deleted before object is saved. Use ``append`` if you don't wish this to happen. :param append: (optional) If ``True``, then if the file exists, then only the particular path in the file will get written/overwritten. If ``False`` and both file and path exist, then an ``IOError`` will be raised. If ``False`` and file exists but not path, then no error will be raised. """
if os.path.exists(filename): with pd.HDFStore(filename) as store: if path in store: if overwrite: os.remove(filename) elif not append: raise IOError('{} in {} exists. '.format(path,filename) + 'Set either overwrite or append option.') if properties is None: properties = {} for prop in self._properties: properties[prop] = getattr(self, prop) self.stars.to_hdf(filename,'{}/stars'.format(path)) self.constraint_df.to_hdf(filename,'{}/constraints'.format(path)) if self.orbpop is not None: self.orbpop.save_hdf(filename, path=path+'/orbpop') with pd.HDFStore(filename) as store: attrs = store.get_storer('{}/stars'.format(path)).attrs attrs.selectfrac_skip = self.selectfrac_skip attrs.distribution_skip = self.distribution_skip attrs.name = self.name attrs.poptype = type(self) attrs.properties = properties
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_hdf(cls, filename, path=''): """Loads StarPopulation from .h5 file Correct properties should be restored to object, and object will be original type that was saved. Complement to :func:`StarPopulation.save_hdf`. Example usage:: True True :param filename: HDF file with saved :class:`StarPopulation`. :param path: Path within HDF file. :return: :class:`StarPopulation` or appropriate subclass; whatever was saved with :func:`StarPopulation.save_hdf`. """
stars = pd.read_hdf(filename,path+'/stars') constraint_df = pd.read_hdf(filename,path+'/constraints') with pd.HDFStore(filename) as store: has_orbpop = '{}/orbpop/df'.format(path) in store has_triple_orbpop = '{}/orbpop/long/df'.format(path) in store attrs = store.get_storer('{}/stars'.format(path)).attrs poptype = attrs.poptype new = poptype() #if poptype != type(self): # raise TypeError('Saved population is {}. Please instantiate proper class before loading.'.format(poptype)) distribution_skip = attrs.distribution_skip selectfrac_skip = attrs.selectfrac_skip name = attrs.name for kw,val in attrs.properties.items(): setattr(new, kw, val) #load orbpop if there orbpop = None if has_orbpop: orbpop = OrbitPopulation.load_hdf(filename, path=path+'/orbpop') elif has_triple_orbpop: orbpop = TripleOrbitPopulation.load_hdf(filename, path=path+'/orbpop') new.stars = stars new.orbpop = orbpop for n in constraint_df.columns: mask = np.array(constraint_df[n]) c = Constraint(mask,name=n) sel_skip = n in selectfrac_skip dist_skip = n in distribution_skip new.apply_constraint(c,selectfrac_skip=sel_skip, distribution_skip=dist_skip) return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary_fraction(self,query='mass_A >= 0'): """ Binary fraction of stars passing given query :param query: Query to pass to stars ``DataFrame``. """
subdf = self.stars.query(query) nbinaries = (subdf['mass_B'] > 0).sum() frac = nbinaries/len(subdf) return frac, frac/np.sqrt(nbinaries)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmag(self,band): """ Difference in magnitude between primary and secondary stars :param band: Photometric bandpass. """
mag2 = self.stars['{}_mag_B'.format(band)] mag1 = self.stars['{}_mag_A'.format(band)] return mag2-mag1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rsky_distribution(self,rmax=None,smooth=0.1,nbins=100): """ Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin width for histogram :param smooth: (optional) Smoothing parameter for :class:`simpledists.Hist_Distribution` :param nbins: (optional) Number of bins for histogram :return: :class:`simpledists.Hist_Distribution` describing Rsky distribution """
if rmax is None: if hasattr(self,'maxrad'): rmax = self.maxrad else: rmax = np.percentile(self.Rsky,99) dist = dists.Hist_Distribution(self.Rsky.value,bins=nbins,maxval=rmax,smooth=smooth) return dist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self, M, age=9.6, feh=0.0, ichrone='mist', n=1e4, bands=None, **kwargs): """ Function that generates population. Called by ``__init__`` if ``M`` is passed. """
ichrone = get_ichrone(ichrone, bands=bands) if np.size(M) > 1: n = np.size(M) else: n = int(n) M2 = M * self.q_fn(n, qmin=np.maximum(self.qmin,self.minmass/M)) P = self.P_fn(n) ecc = self.ecc_fn(n,P) mass = np.ascontiguousarray(np.ones(n)*M) mass2 = np.ascontiguousarray(M2) age = np.ascontiguousarray(age) feh = np.ascontiguousarray(feh) pri = ichrone(mass, age, feh, return_df=True, bands=bands) sec = ichrone(mass2, age, feh, return_df=True, bands=bands) BinaryPopulation.__init__(self, primary=pri, secondary=sec, period=P, ecc=ecc, **kwargs) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmag(self, band): """ Difference in magnitudes between fainter and brighter components in band. :param band: Photometric bandpass. """
m1 = self.stars['{}_mag_A'.format(band)] m2 = addmags(self.stars['{}_mag_B'.format(band)], self.stars['{}_mag_C'.format(band)]) return np.abs(m2-m1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dRV(self, dt, band='g'): """Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter """
return (self.orbpop.dRV_1(dt)*self.A_brighter(band) + self.orbpop.dRV_2(dt)*self.BC_brighter(band))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triple_fraction(self,query='mass_A > 0', unc=False): """ Triple fraction of stars following given query """
subdf = self.stars.query(query) ntriples = ((subdf['mass_B'] > 0) & (subdf['mass_C'] > 0)).sum() frac = ntriples/len(subdf) if unc: return frac, frac/np.sqrt(ntriples) else: return frac
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def starmodel_props(self): """Default mag_err is 0.05, arbitrarily """
props = {} mags = self.mags mag_errs = self.mag_errs for b in mags.keys(): if np.size(mags[b])==2: props[b] = mags[b] elif np.size(mags[b])==1: mag = mags[b] try: e_mag = mag_errs[b] except: e_mag = 0.05 props[b] = (mag, e_mag) if self.Teff is not None: props['Teff'] = self.Teff if self.logg is not None: props['logg'] = self.logg if self.feh is not None: props['feh'] = self.feh return props
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmag(self,band): """ Magnitude difference between primary star and BG stars """
if self.mags is None: raise ValueError('dmag is not defined because primary mags are not defined for this population.') return self.stars['{}_mag'.format(band)] - self.mags[band]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive(self): """I receive data+hash, check for a match, confirm or not confirm to the sender, and return the data payload. """
def _receive(input_message): self.data = input_message[:-64] _hash = input_message[-64:] if h.sha256(self.data).hexdigest() == _hash: self._w.send_message('Confirmed!') else: self._w.send_message('Not Confirmed!') yield self.start_tor() self._w = wormhole.create(u'axotor', RENDEZVOUS_RELAY, self._reactor, tor=self._tor, timing=self._timing) self._w.set_code(self._code) yield self._w.get_message().addCallback(_receive) yield self._w.close() self._reactor.stop() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validator(ch): """ Update screen if necessary and release the lock so receiveThread can run """
global screen_needs_update try: if screen_needs_update: curses.doupdate() screen_needs_update = False return ch finally: winlock.release() sleep(0.01) # let receiveThread in if necessary winlock.acquire()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(self, inds): """Returns copy of constraint, with mask rearranged according to indices """
new = copy.deepcopy(self) for arr in self.arrays: x = getattr(new, arr) setattr(new, arr, x[inds]) return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, overwrite=True): """ Saves PopulationSet and TransitSignal. Shouldn't need to use this if you're using :func:`FPPCalculation.from_ini`. Saves :class`PopulationSet` to ``[folder]/popset.h5]`` and :class:`TransitSignal` to ``[folder]/trsig.pkl``. :param overwrite: (optional) Whether to overwrite existing files. """
self.save_popset(overwrite=overwrite) self.save_signal()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(cls, folder): """ Loads PopulationSet from folder ``popset.h5`` and ``trsig.pkl`` must exist in folder. :param folder: Folder from which to load. """
popset = PopulationSet.load_hdf(os.path.join(folder,'popset.h5')) sigfile = os.path.join(folder,'trsig.pkl') with open(sigfile, 'rb') as f: trsig = pickle.load(f) return cls(trsig, popset, folder=folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FPPplots(self, folder=None, format='png', tag=None, **kwargs): """ Make FPP diagnostic plots Makes likelihood "fuzz plot" for each model, a FPP summary figure, a plot of the :class:`TransitSignal`, and writes a ``results.txt`` file. :param folder: (optional) Destination folder for plots/``results.txt``. Default is ``self.folder``. :param format: (optional) :param tag: (optional) If this is provided (string), then filenames will have ``_[tag]`` appended to the filename, before the extension. :param **kwargs: Additional keyword arguments passed to :func:`PopulationSet.lhoodplots`. """
if folder is None: folder = self.folder self.write_results(folder=folder) self.lhoodplots(folder=folder,figformat=format,tag=tag,**kwargs) self.FPPsummary(folder=folder,saveplot=True,figformat=format,tag=tag) self.plotsignal(folder=folder,saveplot=True,figformat=format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_results(self,folder=None, filename='results.txt', to_file=True): """ Writes text file of calculation summary. :param folder: (optional) Folder to which to write ``results.txt``. :param filename: Filename to write. Default=``results.txt``. :param to_file: If True, then writes file. Otherwise just return header, line. :returns: Header string, line """
if folder is None: folder = self.folder if to_file: fout = open(os.path.join(folder,filename), 'w') header = '' for m in self.popset.shortmodelnames: header += 'lhood_{0} L_{0} pr_{0} '.format(m) header += 'fpV fp FPP' if to_file: fout.write('{} \n'.format(header)) Ls = {} Ltot = 0 lhoods = {} for model in self.popset.modelnames: lhoods[model] = self.lhood(model) Ls[model] = self.prior(model)*lhoods[model] Ltot += Ls[model] line = '' for model in self.popset.modelnames: line += '%.2e %.2e %.2e ' % (lhoods[model], Ls[model], Ls[model]/Ltot) line += '%.3g %.3f %.2e' % (self.fpV(),self.priorfactors['fp_specific'],self.FPP()) if to_file: fout.write(line+'\n') fout.close() return header, line