Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_by_name(cls, name):
        try:
            return cls.query.filter_by(name=name).one()
        except NoResultFound:
            return None

Response: Query group by a group name.


Instruction:
Implement a function in Python 3 to
query by a list of group names.

Response:
def query_by_names(cls, names):
        """Query group by a list of group names.

        :param list names: List of the group names.
        :returns: Query object.
        """
        assert isinstance(names, list)
        return cls.query.filter(cls.name.in_(names))


Instruction:
Given the following Python 3 function, write the documentation
def query_by_user(cls, user, with_pending=False, eager=False):
        q1 = Group.query.join(Membership).filter_by(user_id=user.get_id())
        if not with_pending:
            q1 = q1.filter_by(state=MembershipState.ACTIVE)
        if eager:
            q1 = q1.options(joinedload(Group.members))

        q2 = Group.query.join(GroupAdmin).filter_by(
            admin_id=user.get_id(), admin_type=resolve_admin_type(user))
        if eager:
            q2 = q2.options(joinedload(Group.members))

        query = q1.union(q2).with_entities(Group.id)

        return Group.query.filter(Group.id.in_(query))

Response: Query group by user.


Instruction:
Given the following Python 3 function, write the documentation
def search(cls, query, q):
        return query.filter(Group.name.like('%{0}%'.format(q)))

Response: Modify query as so include only specific group names.


Instruction:
Here you have a function in Python 3, explain what it does
def add_member(self, user, state=MembershipState.ACTIVE):
        return Membership.create(self, user, state)

Response: Invite a user to a group.


Instruction:
Write a Python 3 function that can
invite a user to a group.

Response:
def invite(self, user, admin=None):
        """Invite a user to a group (should be done by admins).

        Wrapper around ``add_member()`` to ensure proper membership state.

        :param user: User to invite.
        :param admin: Admin doing the action. If provided, user is only invited
            if the object is an admin for this group. Default: None.
        :returns: Newly created Membership or None.
        """
        if admin is None or self.is_admin(admin):
            return self.add_member(user, state=MembershipState.PENDING_USER)
        return None


Instruction:
How would you implement a function in Python 3 that
invites users to a group by emails.

Response:
def invite_by_emails(self, emails):
        """Invite users to a group by emails.

        :param list emails: Emails of users that shall be invited.
        :returns list: Newly created Memberships or Nones.
        """
        assert emails is None or isinstance(emails, list)

        results = []

        for email in emails:
            try:
                user = User.query.filter_by(email=email).one()
                results.append(self.invite(user))
            except NoResultFound:
                results.append(None)

        return results


Instruction:
Implement a Python 3 function for
subscribing a user to a group.

Response:
def subscribe(self, user):
        """Subscribe a user to a group (done by users).

        Wrapper around ``add_member()`` which checks subscription policy.

        :param user: User to subscribe.
        :returns: Newly created Membership or None.
        """
        if self.subscription_policy == SubscriptionPolicy.OPEN:
            return self.add_member(user)
        elif self.subscription_policy == SubscriptionPolicy.APPROVAL:
            return self.add_member(user, state=MembershipState.PENDING_ADMIN)
        elif self.subscription_policy == SubscriptionPolicy.CLOSED:
            return None


Instruction:
Can you implement a function in Python 3 that
verifies if given user is a group member.

Response:
def is_member(self, user, with_pending=False):
        """Verify if given user is a group member.

        :param user: User to be checked.
        :param bool with_pending: Whether to include pending users or not.
        :returns: True or False.
        """
        m = Membership.get(self, user)
        if m is not None:
            if with_pending:
                return True
            elif m.state == MembershipState.ACTIVE:
                return True
        return False


Instruction:
Can you tell what is the following Python 3 function doing
def can_see_members(self, user):
        if self.privacy_policy == PrivacyPolicy.PUBLIC:
            return True
        elif self.privacy_policy == PrivacyPolicy.MEMBERS:
            return self.is_member(user) or self.is_admin(user)
        elif self.privacy_policy == PrivacyPolicy.ADMINS:
            return self.is_admin(user)

Response: Determine if given user can see other group members.


Instruction:
Write a Python 3 script for
determining if a user can invite people to a group.

Response:
def can_invite_others(self, user):
        """Determine if user can invite people to a group.

        Be aware that this check is independent from the people (users) which
        are going to be invited. The checked user is the one who invites
        someone, NOT who is going to be invited.

        :param user: User to be checked.
        :returns: True or False.
        """
        if self.is_managed:
            return False
        elif self.is_admin(user):
            return True
        elif self.subscription_policy != SubscriptionPolicy.CLOSED:
            return True
        else:
            return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(cls, group, user):
        try:
            m = cls.query.filter_by(user_id=user.get_id(), group=group).one()
            return m
        except Exception:
            return None

Response: Get the membership for given user and group.


Instruction:
How would you implement a function in Python 3 that
filters a query result.

Response:
def _filter(cls, query, state=MembershipState.ACTIVE, eager=None):
        """Filter a query result."""
        query = query.filter_by(state=state)

        eager = eager or []
        for field in eager:
            query = query.options(joinedload(field))

        return query


Instruction:
Given the following Python 3 function, write the documentation
def query_by_user(cls, user, **kwargs):
        return cls._filter(
            cls.query.filter_by(user_id=user.get_id()),
            **kwargs
        )

Response: Get a user s memberships.


Instruction:
Can you tell what is the following Python 3 function doing
def query_invitations(cls, user, eager=False):
        if eager:
            eager = [Membership.group]
        return cls.query_by_user(user, state=MembershipState.PENDING_USER,
                                 eager=eager)

Response: Get all invitations for given user.


Instruction:
Here you have a function in Python 3, explain what it does
def query_requests(cls, admin, eager=False):
        # Get direct pending request
        if hasattr(admin, 'is_superadmin') and admin.is_superadmin:
            q1 = GroupAdmin.query.with_entities(
                GroupAdmin.group_id)
        else:
            q1 = GroupAdmin.query_by_admin(admin).with_entities(
                GroupAdmin.group_id)
        q2 = Membership.query.filter(
            Membership.state == MembershipState.PENDING_ADMIN,
            Membership.id_group.in_(q1),
        )

        # Get request from admin groups your are member of
        q3 = Membership.query_by_user(
            user=admin, state=MembershipState.ACTIVE
        ).with_entities(Membership.id_group)
        q4 = GroupAdmin.query.filter(
            GroupAdmin.admin_type == 'Group', GroupAdmin.admin_id.in_(q3)
        ).with_entities(GroupAdmin.group_id)
        q5 = Membership.query.filter(
            Membership.state == MembershipState.PENDING_ADMIN,
            Membership.id_group.in_(q4))

        query = q2.union(q5)

        return query

Response: Get all pending group requests.


Instruction:
Explain what the following Python 3 code does
def query_by_group(cls, group_or_id, with_invitations=False, **kwargs):
        if isinstance(group_or_id, Group):
            id_group = group_or_id.id
        else:
            id_group = group_or_id

        if not with_invitations:
            return cls._filter(
                cls.query.filter_by(id_group=id_group),
                **kwargs
            )
        else:
            return cls.query.filter(
                Membership.id_group == id_group,
                db.or_(
                    Membership.state == MembershipState.PENDING_USER,
                    Membership.state == MembershipState.ACTIVE
                )
            )

Response: Get a group s members.


Instruction:
Given the following Python 3 function, write the documentation
def search(cls, query, q):
        query = query.join(User).filter(
                User.email.like('%{0}%'.format(q)),
        )
        return query

Response: Modify query as so include only specific members.


Instruction:
How would you implement a function in Python 3 that
modifies query as so to order the results.

Response:
def order(cls, query, field, s):
        """Modify query as so to order the results.

        :param query: Query object.
        :param str s: Orderinig: ``asc`` or ``desc``.
        :returs: Query object.
        """
        if s == 'asc':
            query = query.order_by(asc(field))
        elif s == 'desc':
            query = query.order_by(desc(field))
        return query


Instruction:
How would you explain what the following Python 3 function does
def create(cls, group, user, state=MembershipState.ACTIVE):
        with db.session.begin_nested():
            membership = cls(
                user_id=user.get_id(),
                id_group=group.id,
                state=state,
            )
            db.session.add(membership)
        return membership

Response: Create a new membership.


Instruction:
Write a Python 3 script for
creating a new group admin.

Response:
def create(cls, group, admin):
        """Create a new group admin.

        :param group: Group object.
        :param admin: Admin object.
        :returns: Newly created GroupAdmin object.
        :raises: IntegrityError
        """
        with db.session.begin_nested():
            obj = cls(
                group=group,
                admin=admin,
            )
            db.session.add(obj)
        return obj


Instruction:
Create a Python 3 function to
get specific GroupAdmin object.

Response:
def get(cls, group, admin):
        """Get specific GroupAdmin object."""
        try:
            ga = cls.query.filter_by(
                group=group, admin_id=admin.get_id(),
                admin_type=resolve_admin_type(admin)).one()
            return ga
        except Exception:
            return None


Instruction:
Explain what the following Python 3 code does
def delete(cls, group, admin):
        with db.session.begin_nested():
            obj = cls.query.filter(
                cls.admin == admin, cls.group == group).one()
            db.session.delete(obj)

Response: Delete admin from group.


Instruction:
Implement a Python 3 function for
getting all groups for a specific admin.

Response:
def query_by_admin(cls, admin):
        """Get all groups for for a specific admin."""
        return cls.query.filter_by(
            admin_type=resolve_admin_type(admin), admin_id=admin.get_id())


Instruction:
Given the following Python 3 function, write the documentation
def query_admins_by_group_ids(cls, groups_ids=None):
        assert groups_ids is None or isinstance(groups_ids, list)

        query = db.session.query(
            Group.id, func.count(GroupAdmin.id)
        ).join(
            GroupAdmin
        ).group_by(
            Group.id
        )

        if groups_ids:
            query = query.filter(Group.id.in_(groups_ids))

        return query

Response: Get count of admins per group.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def all(self):
    '''
      Get all social newtworks profiles
    '''

    response = self.api.get(url=PATHS['GET_PROFILES'])

    for raw_profile in response:
      self.append(Profile(self.api, raw_profile))

    return self

Response: Get all social newtworks profiles


Instruction:
Create a Python 3 function to
return a new Profiles object containing only the items chosen by some criteria

Response:
def filter(self, **kwargs):
    '''
      Based on some criteria, filter the profiles and return a new Profiles
      Manager containing only the chosen items

      If the manager doen't have any items, get all the profiles from Buffer
    '''

    if not len(self):
      self.all()

    new_list = filter(lambda item: [True for arg in kwargs if item[arg] == kwargs[arg]] != [], self)

    return Profiles(self.api, new_list)


Instruction:
Can you generate the documentation for the following Python 3 function
def dorun(SNR=20, sweeps=20, burn=8, noise_samples=10):
    radii = np.linspace(2,10,8, endpoint=False)
    crbs, vals, errs = [], [], []

    for radius in radii:
        print 'radius', radius
        s,im = pxint(radius=radius, factor=4)
        goodstate = s.state.copy()

        common.set_image(s, im, 1.0/SNR)
        tcrb = crb(s)
        tval, terr = sample(s, im, 1.0/SNR, N=noise_samples, sweeps=sweeps, burn=burn)
        crbs.append(tcrb)
        vals.append(tval)
        errs.append(terr)

    return np.array(crbs), np.array(vals), np.array(errs), radii

Response: This function is used to plot the errors introduced by pixelation so we plot the CRB for the current node and the image of the next node.


Instruction:
Create a Python 3 function to
return the skew parameter for direction d

Response:
def _skew(self, x, z, d=0):
        """ returns the kurtosis parameter for direction d, d=0 is rho, d=1 is z """
        # get the top bound determined by the kurtosis
        kval = (np.tanh(self._poly(z, self._kurtosis_coeffs(d)))+1)/12.
        bdpoly = np.array([
            -1.142468e+04,  3.0939485e+03, -2.0283568e+02,
            -2.1047846e+01, 3.79808487e+00, 1.19679781e-02
        ])
        top = np.polyval(bdpoly, kval)

        # limit the skewval to be 0 -> top val
        skew = self._poly(z, self._skew_coeffs(d))
        skewval = top*(np.tanh(skew) + 1) - top

        return skewval*(3*x - x**3)


Instruction:
Write a Python 3 function for
returning the kurtosis parameter for direction d

Response:
def _kurtosis(self, x, z, d=0):
        """ returns the kurtosis parameter for direction d, d=0 is rho, d=1 is z """
        val = self._poly(z, self._kurtosis_coeffs(d))
        return (np.tanh(val)+1)/12.*(3 - 6*x**2 + x**4)


Instruction:
Can you create a Python 3 function that
fits a separation of two parties into a single edge

Response:
def fit_edge(separation, radius=5.0, samples=100, imsize=64, sigma=0.05, axis='z'):
    """
    axis is 'z' or 'xy'
    seps = np.linspace(0,2,20) 'z'
    seps = np.linspace(-2,2,20) 'xy'
    """
    terrors = []
    berrors = []
    crbs = []

    for sep in separation:
        print '='*79
        print 'sep =', sep,

        s = init.create_two_particle_state(imsize, radius=radius, delta=sep, sigma=0.05,
                axis='z', psfargs={'params': (2.0,1.0,4.0), 'error': 1e-8},
                          stateargs={'sigmapad': True, 'pad': const.PAD})

        # move off of a pixel edge (cheating for trackpy)
        d = np.array([0,0.5,0.5])
        s.obj.pos -= d
        s.reset()

        # move the particles to the edge
        bl = s.blocks_particle(0)
        s.update(bl[0], np.array([s.pad+radius]))

        bl = s.blocks_particle(1)
        s.update(bl[0], np.array([s.pad-radius]))

        if axis == 'z':
            bl = s.blocks_particle(1)
            s.update(bl[0], s.state[bl[0]]-sep)
            s.model_to_true_image()

        if axis == 'xy':
            bl = s.blocks_particle(1)
            s.update(bl[2], s.state[bl[2]]+sep)
            s.model_to_true_image()

        # save where the particles were originally so we can jiggle
        p = s.state[s.b_pos].reshape(-1,3).copy()

        print p[0], p[1]
        # calculate the CRB for this configuration
        bl = s.explode(s.b_pos)
        crbs.append(np.sqrt(np.diag(np.linalg.inv(s.fisher_information(blocks=bl)))).reshape(-1,3))

        # calculate the featuring errors
        tmp_tp, tmp_bf = [],[]
        for i in xrange(samples):
            print i
            bench.jiggle_particles(s, pos=p, sig=0.3, mask=np.array([1,1,1]))
            t = bench.trackpy(s)
            b = bench.bamfpy_positions(s, sweeps=15)

            tmp_tp.append(bench.error(s, t))
            tmp_bf.append(bench.error(s, b))
        terrors.append(tmp_tp)
        berrors.append(tmp_bf)

    return np.array(crbs), np.array(terrors), np.array(berrors)


Instruction:
How would you explain what the following Python 3 function does
def zjitter(jitter=0.0, radius=5):
    psfsize = np.array([2.0, 1.0, 3.0])

    # create a base image of one particle
    s0 = init.create_single_particle_state(imsize=4*radius,
            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})
    sl = np.s_[s0.pad:-s0.pad,s0.pad:-s0.pad,s0.pad:-s0.pad]

    # add up a bunch of trajectories
    finalimage = 0*s0.get_model_image()[sl]
    position = 0*s0.obj.pos[0]

    for i in xrange(finalimage.shape[0]):
        offset = jitter*np.random.randn(3)*np.array([1,0,0])
        s0.obj.pos[0] = np.array(s0.image.shape)/2 + offset
        s0.reset()

        finalimage[i] = s0.get_model_image()[sl][i]
        position += s0.obj.pos[0]

    position /= float(finalimage.shape[0])

    # place that into a new image at the expected parameters
    s = init.create_single_particle_state(imsize=4*radius, sigma=0.05,
            radius=radius, psfargs={'params': psfsize, 'error': 1e-6})
    s.reset()

    # measure the true inferred parameters
    return s, finalimage, position

Response: create a new state and a base image of one particle and a random position


Instruction:
Here you have a function in Python 3, explain what it does
def dorun(SNR=20, njitters=20, samples=10, noise_samples=10, sweeps=20, burn=10):
    jitters = np.logspace(-6, np.log10(0.5), njitters)
    crbs, vals, errs, poss = [], [], [], []

    for i,t in enumerate(jitters):
        print '###### jitter', i, t

        for j in xrange(samples):
            print 'image', j, '|',
            s,im,pos = zjitter(jitter=t)

            # typical image
            common.set_image(s, im, 1.0/SNR)
            crbs.append(crb(s))

            val, err = sample(s, im, 1.0/SNR, N=noise_samples, sweeps=sweeps, burn=burn)
            poss.append(pos)
            vals.append(val)
            errs.append(err)

    shape0 = (njitters, samples, -1)
    shape1 = (njitters, samples, noise_samples, -1)

    crbs = np.array(crbs).reshape(shape0)
    vals = np.array(vals).reshape(shape1)
    errs = np.array(errs).reshape(shape1)
    poss = np.array(poss).reshape(shape0)

    return  [crbs, vals, errs, poss, jitters]

Response: This function is used to plot the errors introduced by pixelation so we plot the crbs and values and errors for the next time.


Instruction:
Write a Python 3 script for
returning the detailed information on individual interactions with the social media update such as favorites retweets and likes.

Response:
def interactions(self):
    '''
      Returns the detailed information on individual interactions with the social
      media update such as favorites, retweets and likes.
    '''

    interactions = []
    url = PATHS['GET_INTERACTIONS'] % self.id

    response = self.api.get(url=url)
    for interaction in response['interactions']:
      interactions.append(ResponseObject(interaction))

    self.__interactions = interactions

    return self.__interactions


Instruction:
Given the following Python 3 function, write the documentation
def edit(self, text, media=None, utc=None, now=None):
    '''
      Edit an existing, individual status update.
    '''

    url = PATHS['EDIT'] % self.id

    post_data = "text=%s&" % text

    if now:
      post_data += "now=%s&" % now

    if utc:
      post_data += "utc=%s&" % utc

    if media:
      media_format = "media[%s]=%s&"

      for media_type, media_item in media.iteritems():
        post_data += media_format % (media_type, media_item)

    response = self.api.post(url=url, data=post_data)

    return Update(api=self.api, raw_response=response['update'])

Response: Edit an existing individual status update.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def publish(self):
    '''
      Immediately shares a single pending update and recalculates times for
      updates remaining in the queue.
    '''

    url = PATHS['PUBLISH'] % self.id
    return self.api.post(url=url)

Response: Publishes a single pending update and recalculates times for all updates remaining in the queue.


Instruction:
Can you generate the documentation for the following Python 3 function
def move_to_top(self):
    '''
      Move an existing status update to the top of the queue and recalculate
      times for all updates in the queue. Returns the update with its new
      posting time.
    '''

    url = PATHS['MOVE_TO_TOP'] % self.id

    response = self.api.post(url=url)
    return Update(api=self.api, raw_response=response)

Response:
Move an existing status update to the top of the queue and recalculate the time for all updates in the queue. Returns the updated update with the new
      posting time.


Instruction:
Implement a function in Python 3 to
remove the noise poles from a 2d noise distribution to show that affects the real-space noise picture. noise -- fftshifted 2d array of q values poles -- N,2 list of pole locations. the last index is in the order y,x as determined by mpl interactive plots for example: poles = np.array([[190,277], [227,253], [233, 256]]

Response:
def pole_removal(noise, poles=None, sig=3):
    """
    Remove the noise poles from a 2d noise distribution to show that affects
    the real-space noise picture.

    noise -- fftshifted 2d array of q values

    poles -- N,2 list of pole locations. the last index is in the order y,x as
    determined by mpl interactive plots

    for example: poles = np.array([[190,277], [227,253], [233, 256]]
    """
    center = np.array(noise.shape)/2

    v = np.rollaxis(
            np.array(
                np.meshgrid(*(np.arange(s) for s in noise.shape), indexing='ij')
            ), 0, 3
        ).astype("float")
    filter = np.zeros_like(noise, dtype='float')

    for p in poles:
        for pp in [p, center - (p-center)]:
            dist = ((v-pp)**2).sum(axis=-1)
            filter += np.exp(-dist / (2*sig**2))

    filter[filter > 1] = 1
    return noise*(1-filter)


Instruction:
Given the following Python 3 function, write the documentation
def pending(self):
    '''
      Returns an array of updates that are currently in the buffer for an
      individual social media profile.
    '''

    pending_updates = []
    url = PATHS['GET_PENDING'] % self.profile_id

    response = self.api.get(url=url)
    for update in response['updates']:
      pending_updates.append(Update(api=self.api, raw_response=update))

    self.__pending = pending_updates

    return self.__pending

Response: Returns an array of updates that are currently in the buffer for an individual social media profile.


Instruction:
Here you have a function in Python 3, explain what it does
def sent(self):
    '''
      Returns an array of updates that have been sent from the buffer for an
      individual social media profile.
    '''

    sent_updates = []
    url = PATHS['GET_SENT'] % self.profile_id

    response = self.api.get(url=url)
    for update in response['updates']:
      sent_updates.append(Update(api=self.api, raw_response=update))

    self.__sent = sent_updates

    return self.__sent

Response: Returns an array of updates that have been sent from the buffer for an individual social media profile.


Instruction:
Make a summary of the following Python 3 code
def shuffle(self, count=None, utc=None):
    '''
      Randomize the order at which statuses for the specified social media
      profile will be sent out of the buffer.
    '''

    url = PATHS['SHUFFLE'] % self.profile_id

    post_data = ''
    if count:
      post_data += 'count=%s&' % count
    if utc:
      post_data += 'utc=%s' % utc

    return self.api.post(url=url, data=post_data)

Response: Randomize the order at which statuses for the specified social media offer will be sent out of the buffer.


Instruction:
How would you explain what the following Python 3 function does
def reorder(self, updates_ids, offset=None, utc=None):
    '''
      Edit the order at which statuses for the specified social media profile will
      be sent out of the buffer.
    '''

    url = PATHS['REORDER'] % self.profile_id

    order_format = "order[]=%s&"
    post_data = ''

    if offset:
      post_data += 'offset=%s&' % offset

    if utc:
      post_data += 'utc=%s&' % utc

    for update in updates_ids:
      post_data += order_format % update

    return self.api.post(url=url, data=post_data)

Response: This method is used to reorder the items in a social media profile.


Instruction:
Create a Python 3 function to
create one or more new status updates.

Response:
def new(self, text, shorten=None, now=None, top=None, media=None, when=None):
    '''
      Create one or more new status updates.
    '''

    url = PATHS['CREATE']

    post_data = "text=%s&" % text
    post_data += "profile_ids[]=%s&" % self.profile_id

    if shorten:
      post_data += "shorten=%s&" % shorten

    if now:
      post_data += "now=%s&" % now

    if top:
      post_data += "top=%s&" % top

    if when:
      post_data += "scheduled_at=%s&" % str(when)

    if media:
      media_format = "media[%s]=%s&"

      for media_type, media_item in media.iteritems():
        post_data += media_format % (media_type, media_item)

    response = self.api.post(url=url, data=post_data)
    new_update = Update(api=self.api, raw_response=response['updates'][0])

    self.append(new_update)

    return new_update


Instruction:
Write a Python 3 function that can
set the logging level of the handlers.

Response:
def set_level(self, level='info', handlers=None):
        """
        Set the logging level (which types of logs are actually printed / recorded)
        to one of ['debug', 'info', 'warn', 'error', 'fatal'] in that order
        of severity
        """
        for h in self.get_handlers(handlers):
            h.setLevel(levels[level])


Instruction:
Can you tell what is the following Python 3 function doing
def set_formatter(self, formatter='standard', handlers=None):
        for h in self.get_handlers(handlers):
            h.setFormatter(logging.Formatter(formatters[formatter]))

Response: Set the text format of messages to one of the pre - deterministic forms


Instruction:
Write a Python 3 function that can
add a new handler to the logging system if not present already.

Response:
def add_handler(self, name='console-color', level='info', formatter='standard', **kwargs):
        """
        Add another handler to the logging system if not present already.
        Available handlers are currently: ['console-bw', 'console-color', 'rotating-log']
        """
        # make sure the the log file has a name
        if name == 'rotating-log' and 'filename' not in kwargs:
            kwargs.update({'filename': self.logfilename})

        # make sure the the log file has a name
        if name == 'stringio' and 'stringio' not in kwargs:
            kwargs.update({'stringio': StringIO.StringIO()})

        handler = types[name](**kwargs)
        self.add_handler_raw(handler, name, level=level, formatter=formatter)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def remove_handler(self, name):
        if name in self.handlers:
            self.log.removeHandler(self.handlers[name])

Response: Remove a handler from the logging system if present.


Instruction:
Write a Python 3 function for
setting the verbosity level of a certain log handler or all handlers.

Response:
def set_verbosity(self, verbosity='vvv', handlers=None):
        """
        Set the verbosity level of a certain log handler or of all handlers.

        Parameters
        ----------
        verbosity : 'v' to 'vvvvv'
            the level of verbosity, more v's is more verbose

        handlers : string, or list of strings
            handler names can be found in ``peri.logger.types.keys()``
            Current set is::

                ['console-bw', 'console-color', 'rotating-log']
        """
        self.verbosity = sanitize(verbosity)
        self.set_level(v2l[verbosity], handlers=handlers)
        self.set_formatter(v2f[verbosity], handlers=handlers)


Instruction:
How would you explain what the following Python 3 function does
def normalize(im, invert=False, scale=None, dtype=np.float64):
    if dtype not in {np.float16, np.float32, np.float64}:
        raise ValueError('dtype must be numpy.float16, float32, or float64.')
    out = im.astype('float').copy()

    scale = scale or (0.0, 255.0)
    l, u = (float(i) for i in scale)
    out = (out - l) / (u - l)
    if invert:
        out = -out + (out.max() + out.min())
    return out.astype(dtype)

Response: Normalize a field to a range of exposure values.


Instruction:
Can you create a Python 3 function that
generates a centered boolean mask of a 3D sphere

Response:
def generate_sphere(radius):
    """Generates a centered boolean mask of a 3D sphere"""
    rint = np.ceil(radius).astype('int')
    t = np.arange(-rint, rint+1, 1)
    x,y,z = np.meshgrid(t, t, t, indexing='ij')
    r = np.sqrt(x*x + y*y + z*z)
    sphere = r < radius
    return sphere


Instruction:
Can you generate the documentation for the following Python 3 function
def harris_feature(im, region_size=5, to_return='harris', scale=0.05):
    ndim = im.ndim
    #1. Gradient of image
    grads = [nd.sobel(im, axis=i) for i in range(ndim)]
    #2. Corner response matrix
    matrix = np.zeros((ndim, ndim) + im.shape)
    for a in range(ndim):
        for b in range(ndim):
            matrix[a,b] = nd.filters.gaussian_filter(grads[a]*grads[b],
                    region_size)
    if to_return == 'matrix':
        return matrix
    #3. Trace, determinant
    trc = np.trace(matrix, axis1=0, axis2=1)
    det = np.linalg.det(matrix.T).T
    if to_return == 'trace-determinant':
        return trc, det
    else:
        #4. Harris detector:
        harris = det - scale*trc*trc
        return harris

Response: Harris - motivated feature detection on a d - dimensional image.


Instruction:
How would you implement a function in Python 3 that
identifies slabs in an image. Functions by running a Harris-inspired edge detection on the image, thresholding the edge, then clustering. Parameters ---------- im : numpy.ndarray 3D array of the image to analyze. sigma : Float, optional Gaussian blurring kernel to remove non-slab features such as noise and particles. Default is 5. region_size : Int, optional The size of region for Harris corner featuring. Default is 10 masscut : Float, optional The minimum number of pixels for a feature to be identified as a slab. Default is 1e4; should be smaller for smaller images. asdict : Bool, optional Set to True to return a list of dicts, with keys of ``'theta'`` and ``'phi'`` as rotation angles about the x- and z- axes, and of ``'zpos'`` for the z-position, i.e. a list of dicts which can be unpacked into a :class:``peri.comp.objs.Slab`` Returns ------- [poses, normals] : numpy.ndarray The positions and normals of each slab in the image; ``poses[i]`` and ``normals[i]`` are the ``i``th slab. Returned if ``asdict`` is False [list] A list of dictionaries. Returned if ``asdict`` is True

Response:
def identify_slab(im, sigma=5., region_size=10, masscut=1e4, asdict=False):
    """
    Identifies slabs in an image.

    Functions by running a Harris-inspired edge detection on the image,
    thresholding the edge, then clustering.

    Parameters
    ----------
        im : numpy.ndarray
            3D array of the image to analyze.
        sigma : Float, optional
            Gaussian blurring kernel to remove non-slab features such as
            noise and particles. Default is 5.
        region_size : Int, optional
            The size of region for Harris corner featuring. Default is 10
        masscut : Float, optional
            The minimum number of pixels for a feature to be identified as
            a slab. Default is 1e4; should be smaller for smaller images.
        asdict : Bool, optional
            Set to True to return a list of dicts, with keys of ``'theta'``
            and ``'phi'`` as rotation angles about the x- and z- axes, and
            of ``'zpos'`` for the z-position, i.e. a list of dicts which
            can be unpacked into a :class:``peri.comp.objs.Slab``

    Returns
    -------
        [poses, normals] : numpy.ndarray
            The positions and normals of each slab in the image; ``poses[i]``
            and ``normals[i]`` are the ``i``th slab. Returned if ``asdict``
            is False
        [list]
            A list of dictionaries. Returned if ``asdict`` is True
    """
    #1. edge detect:
    fim = nd.filters.gaussian_filter(im, sigma)
    trc, det = harris_feature(fim, region_size, to_return='trace-determinant')
    #we want an edge == not a corner, so one eigenvalue is high and
    #one is low compared to the other.
    #So -- trc high, normalized det low:
    dnrm = det / (trc*trc)
    trc_cut = otsu_threshold(trc)
    det_cut = otsu_threshold(dnrm)
    slabs = (trc > trc_cut) & (dnrm < det_cut)
    labeled, nslabs = nd.label(slabs)
    #masscuts:
    masses = [(labeled == i).sum() for i in range(1, nslabs+1)]
    good = np.array([m > masscut for m in masses])
    inds = np.nonzero(good)[0] + 1  #+1 b/c the lowest label is the bkg
    #Slabs are identifiied, now getting the coords:
    poses = np.array(nd.measurements.center_of_mass(trc, labeled, inds))
    #normals from eigenvectors of the covariance matrix
    normals = []
    z = np.arange(im.shape[0]).reshape(-1,1,1).astype('float')
    y = np.arange(im.shape[1]).reshape(1,-1,1).astype('float')
    x = np.arange(im.shape[2]).reshape(1,1,-1).astype('float')
    #We also need to identify the direction of the normal:
    gim = [nd.sobel(fim, axis=i) for i in range(fim.ndim)]
    for i, p in zip(range(1, nslabs+1), poses):
        wts = trc * (labeled == i)
        wts /= wts.sum()
        zc, yc, xc = [xi-pi for xi, pi in zip([z,y,x],p.squeeze())]
        cov = [[np.sum(xi*xj*wts) for xi in [zc,yc,xc]] for xj in [zc,yc,xc]]
        vl, vc = np.linalg.eigh(cov)
        #lowest eigenvalue is the normal:
        normal = vc[:,0]
        #Removing the sign ambiguity:
        gn = np.sum([n*g[tuple(p.astype('int'))] for g,n in zip(gim, normal)])
        normal *= np.sign(gn)
        normals.append(normal)
    if asdict:
        get_theta = lambda n: -np.arctan2(n[1], -n[0])
        get_phi = lambda n: np.arcsin(n[2])
        return [{'zpos':p[0], 'angles':(get_theta(n), get_phi(n))}
                for p, n in zip(poses, normals)]
    else:
        return poses, np.array(normals)


Instruction:
How would you code a function in Python 3 to
plot the errors for a single crystal.

Response:
def plot_errors_single(rad, crb, errors, labels=['trackpy', 'peri']):
    fig = pl.figure()
    comps = ['z', 'y', 'x']
    markers = ['o', '^', '*']
    colors = COLORS

    for i in reversed(range(3)):
        pl.plot(rad, crb[:,0,i], lw=2.5, label='CRB-'+comps[i], color=colors[i])

    for c, (error, label) in enumerate(zip(errors, labels)):
        mu = np.sqrt((error**2).mean(axis=1))[:,0,:]
        std = np.std(np.sqrt((error**2)), axis=1)[:,0,:]

        for i in reversed(range(len(mu[0]))):
            pl.plot(rad, mu[:,i], marker=markers[c], color=colors[i], lw=0, label=label+"-"+comps[i], ms=13)

    pl.ylim(1e-3, 8e0)
    pl.semilogy()
    pl.legend(loc='upper left', ncol=3, numpoints=1, prop={"size": 16})
    pl.xlabel(r"radius (pixels)")
    pl.ylabel(r"CRB / $\Delta$ (pixels)")
    """
    ax = fig.add_axes([0.6, 0.6, 0.28, 0.28])
    ax.plot(rad, crb[:,0,:], lw=2.5)
    for c, error in enumerate(errors):
        mu = np.sqrt((error**2).mean(axis=1))[:,0,:]
        std = np.std(np.sqrt((error**2)), axis=1)[:,0,:]

        for i in range(len(mu[0])):
            ax.errorbar(rad, mu[:,i], yerr=std[:,i], fmt=markers[c], color=colors[i], lw=1)
    ax.set_ylim(-0.1, 1.5)
    ax.grid('off')
    """


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sphere_analytical_gaussian(dr, a, alpha=0.2765):
    term1 = 0.5*(erf((dr+2*a)/(alpha*np.sqrt(2))) + erf(-dr/(alpha*np.sqrt(2))))
    term2 = np.sqrt(0.5/np.pi)*(alpha/(dr+a+1e-10)) * (
                np.exp(-0.5*dr**2/alpha**2) - np.exp(-0.5*(dr+2*a)**2/alpha**2)
            )
    return term1 - term2

Response: Analytically calculate the sphere s functional form by convolving the solar system with first order approximation to the sinc a Gaussian.


Instruction:
Implement a Python 3 function for
seeing sphere_analytical_gaussian_exact. I trimmed to terms from the functional form that are essentially zero (1e-8) for r0 > cut (~1.5), a fine approximation for these platonic anyway.

Response:
def sphere_analytical_gaussian_trim(dr, a, alpha=0.2765, cut=1.6):
    """
    See sphere_analytical_gaussian_exact.

    I trimmed to terms from the functional form that are essentially zero (1e-8)
    for r0 > cut (~1.5), a fine approximation for these platonic anyway.
    """
    m = np.abs(dr) <= cut

    # only compute on the relevant scales
    rr = dr[m]
    t = -rr/(alpha*np.sqrt(2))
    q = 0.5*(1 + erf(t)) - np.sqrt(0.5/np.pi)*(alpha/(rr+a+1e-10)) * np.exp(-t*t)

    # fill in the grid, inside the interpolation and outside where values are constant
    ans = 0*dr
    ans[m] = q
    ans[dr >  cut] = 0
    ans[dr < -cut] = 1
    return ans


Instruction:
Create a Python 3 function for
seeing sphere_analytical_gaussian_trim, but implemented in C with fast erf and exp approximations found at Abramowitz and Stegun: Handbook of Mathematical Functions A Fast, Compact Approximation of the Exponential Function The default cut 1.25 was chosen based on the accuracy of fast_erf

Response:
def sphere_analytical_gaussian_fast(dr, a, alpha=0.2765, cut=1.20):
    """
    See sphere_analytical_gaussian_trim, but implemented in C with
    fast erf and exp approximations found at
        Abramowitz and Stegun: Handbook of Mathematical Functions
        A Fast, Compact Approximation of the Exponential Function

    The default cut 1.25 was chosen based on the accuracy of fast_erf
    """

    code = """
    double coeff1 = 1.0/(alpha*sqrt(2.0));
    double coeff2 = sqrt(0.5/pi)*alpha;

    for (int i=0; i<N; i++){
        double dri = dr[i];
        if (dri < cut && dri > -cut){
            double t = -dri*coeff1;
            ans[i] = 0.5*(1+fast_erf(t)) - coeff2/(dri+a+1e-10) * fast_exp(-t*t);
        } else {
            ans[i] = 0.0*(dri > cut) + 1.0*(dri < -cut);
        }
    }
    """

    shape = r.shape
    r = r.flatten()
    N = self.N
    ans = r*0
    pi = np.pi

    inline(code, arg_names=['dr', 'a', 'alpha', 'cut', 'ans', 'pi', 'N'],
            support_code=functions, verbose=0)
    return ans.reshape(shape)


Instruction:
Implement a Python 3 function for
returning the surface of a cubic interpolant constrained to be a sphere.

Response:
def sphere_constrained_cubic(dr, a, alpha):
    """
    Sphere generated by a cubic interpolant constrained to be (1,0) on
    (r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction.
    """
    sqrt3 = np.sqrt(3)

    b_coeff = a*0.5/sqrt3*(1 - 0.6*sqrt3*alpha)/(0.15 + a*a)
    rscl = np.clip(dr, -0.5*sqrt3, 0.5*sqrt3)

    a, d = rscl + 0.5*sqrt3, rscl - 0.5*sqrt3
    return alpha*d*a*rscl + b_coeff*d*a - d/sqrt3


Instruction:
Can you create a Python 3 function that
performs an iterative method to calculate the effective sphere that conserves volume.

Response:
def exact_volume_sphere(rvec, pos, radius, zscale=1.0, volume_error=1e-5,
        function=sphere_analytical_gaussian, max_radius_change=1e-2, args=()):
    """
    Perform an iterative method to calculate the effective sphere that perfectly
    (up to the volume_error) conserves volume.  Return the resulting image
    """
    vol_goal = 4./3*np.pi*radius**3 / zscale
    rprime = radius

    dr = inner(rvec, pos, rprime, zscale=zscale)
    t = function(dr, rprime, *args)
    for i in range(MAX_VOLUME_ITERATIONS):
        vol_curr = np.abs(t.sum())
        if np.abs(vol_goal - vol_curr)/vol_goal < volume_error:
            break

        rprime = rprime + 1.0*(vol_goal - vol_curr) / (4*np.pi*rprime**2)

        if np.abs(rprime - radius)/radius > max_radius_change:
            break

        dr = inner(rvec, pos, rprime, zscale=zscale)
        t = function(dr, rprime, *args)

    return t


Instruction:
Write a Python 3 script to
get the update tile surrounding particle n

Response:
def _tile(self, n):
        """Get the update tile surrounding particle `n` """
        pos = self._trans(self.pos[n])
        return Tile(pos, pos).pad(self.support_pad)


Instruction:
Can you tell what is the following Python 3 function doing
def _p2i(self, param):
        g = param.split('-')
        if len(g) == 3:
            return g[2], int(g[1])
        else:
            raise ValueError('`param` passed as incorrect format')

Response: Convert parameter to indices returns coord index


Instruction:
Create a Python 3 function for
initializing all objects and draw particles

Response:
def initialize(self):
        """Start from scratch and initialize all objects / draw self.particles"""
        self.particles = np.zeros(self.shape.shape, dtype=self.float_precision)

        for p0, arg0 in zip(self.pos, self._drawargs()):
            self._draw_particle(p0, *listify(arg0))


Instruction:
Here you have a function in Python 3, explain what it does
def _vps(self, inds):
        return [j for j in inds if j >= 0 and j < self.N]

Response: Clips a list of inds to be on [ 0 self. N )


Instruction:
Write a Python 3 script to
translate index info to parameter name

Response:
def _i2p(self, ind, coord):
        """ Translate index info to parameter name """
        return '-'.join([self.param_prefix, str(ind), coord])


Instruction:
Write a Python 3 function that can
get the amount of support size required for a particular update.

Response:
def get_update_tile(self, params, values):
        """ Get the amount of support size required for a particular update."""
        doglobal, particles = self._update_type(params)
        if doglobal:
            return self.shape.copy()

        # 1) store the current parameters of interest
        values0 = self.get_values(params)
        # 2) calculate the current tileset
        tiles0 = [self._tile(n) for n in particles]

        # 3) update to newer parameters and calculate tileset
        self.set_values(params, values)
        tiles1 = [self._tile(n) for n in particles]

        # 4) revert parameters & return union of all tiles
        self.set_values(params, values0)
        return Tile.boundingtile(tiles0 + tiles1)


Instruction:
Write a Python 3 function for
updating the particles field given new parameter values

Response:
def update(self, params, values):
        """
        Update the particles field given new parameter values
        """
        #1. Figure out if we're going to do a global update, in which
        #   case we just draw from scratch.
        global_update, particles = self._update_type(params)

        # if we are doing a global update, everything must change, so
        # starting fresh will be faster instead of add subtract
        if global_update:
            self.set_values(params, values)
            self.initialize()
            return

        # otherwise, update individual particles. delete the current versions
        # of the particles update the particles, and redraw them anew at the
        # places given by (params, values)
        oldargs = self._drawargs()
        for n in particles:
            self._draw_particle(self.pos[n], *listify(oldargs[n]), sign=-1)

        self.set_values(params, values)

        newargs = self._drawargs()
        for n in particles:
            self._draw_particle(self.pos[n], *listify(newargs[n]), sign=+1)


Instruction:
Write a Python 3 function for
getting position and radius of one or more particles

Response:
def param_particle(self, ind):
        """ Get position and radius of one or more particles """
        ind = self._vps(listify(ind))
        return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x', 'a']]


Instruction:
Explain what the following Python 3 code does
def param_particle_pos(self, ind):
        ind = self._vps(listify(ind))
        return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x']]

Response: Get position of one or more particles


Instruction:
Explain what the following Python 3 code does
def param_particle_rad(self, ind):
        ind = self._vps(listify(ind))
        return [self._i2p(i, 'a') for i in ind]

Response: Get radius of one or more particles


Instruction:
How would you explain what the following Python 3 function does
def add_particle(self, pos, rad):
        rad = listify(rad)
        # add some zero mass particles to the list (same as not having these
        # particles in the image, which is true at this moment)
        inds = np.arange(self.N, self.N+len(rad))
        self.pos = np.vstack([self.pos, pos])
        self.rad = np.hstack([self.rad, np.zeros(len(rad))])

        # update the parameters globally
        self.setup_variables()
        self.trigger_parameter_change()

        # now request a drawing of the particle plz
        params = self.param_particle_rad(inds)
        self.trigger_update(params, rad)
        return inds

Response: Add a particle or list of particles given by a list of positions and radii.


Instruction:
Make a summary of the following Python 3 code
def remove_particle(self, inds):
        if self.rad.shape[0] == 0:
            return

        inds = listify(inds)

        # Here's the game plan:
        #   1. get all positions and sizes of particles that we will be
        #      removing (to return to user)
        #   2. redraw those particles to 0.0 radius
        #   3. remove the particles and trigger changes
        # However, there is an issue -- if there are two particles at opposite
        # ends of the image, it will be significantly slower than usual
        pos = self.pos[inds].copy()
        rad = self.rad[inds].copy()

        self.trigger_update(self.param_particle_rad(inds), np.zeros(len(inds)))

        self.pos = np.delete(self.pos, inds, axis=0)
        self.rad = np.delete(self.rad, inds, axis=0)

        # update the parameters globally
        self.setup_variables()
        self.trigger_parameter_change()
        return np.array(pos).reshape(-1,3), np.array(rad).reshape(-1)

Response: Removes the particle at the given indices. Returns the positions and radius of the particle at the given indices.


Instruction:
Can you generate the documentation for the following Python 3 function
def _update_type(self, params):
        dozscale = False
        particles = []
        for p in listify(params):
            typ, ind = self._p2i(p)
            particles.append(ind)
            dozscale = dozscale or typ == 'zscale'
        particles = set(particles)
        return dozscale, particles

Response: Returns the dozscale and particle list of update


Instruction:
Make a summary of the following Python 3 code
def _tile(self, n):
        zsc = np.array([1.0/self.zscale, 1, 1])
        pos, rad = self.pos[n], self.rad[n]
        pos = self._trans(pos)
        return Tile(pos - zsc*rad, pos + zsc*rad).pad(self.support_pad)

Response: Get the tile surrounding particle n


Instruction:
How would you explain what the following Python 3 function does
def update(self, params, values):
        # radparams = self.param_radii()
        params = listify(params)
        values = listify(values)
        for i, p in enumerate(params):
            # if (p in radparams) & (values[i] < 0):
            if (p[-2:] == '-a') and (values[i] < 0):
                values[i] = 0.0
        super(PlatonicSpheresCollection, self).update(params, values)

Response: Calls an update but clips radii to be > 0


Instruction:
Can you generate a brief explanation for the following Python 3 code
def rmatrix(self):
        t = self.param_dict[self.lbl_theta]
        r0 = np.array([ [np.cos(t),  -np.sin(t), 0],
                        [np.sin(t), np.cos(t), 0],
                        [0, 0, 1]])

        p = self.param_dict[self.lbl_phi]
        r1 = np.array([ [np.cos(p), 0, np.sin(p)],
                        [0, 1, 0],
                        [-np.sin(p), 0, np.cos(p)]])
        return np.dot(r1, r0)

Response: Generate the composite rotation matrix that rotates the slab normal.


Instruction:
Given the following Python 3 function, write the documentation
def j2(x):
    to_return = 2./(x+1e-15)*j1(x) - j0(x)
    to_return[x==0] = 0
    return to_return

Response: A fast j2 function that returns the value of x.


Instruction:
Given the following Python 3 function, write the documentation
def calc_pts_hg(npts=20):
    pts_hg, wts_hg = np.polynomial.hermite.hermgauss(npts*2)
    pts_hg = pts_hg[npts:]
    wts_hg = wts_hg[npts:] * np.exp(pts_hg*pts_hg)
    return pts_hg, wts_hg

Response: Calculates the quadrature points for even functions


Instruction:
Explain what the following Python 3 code does
def calc_pts_lag(npts=20):
    scl = { 15:0.072144,
            20:0.051532,
            25:0.043266}[npts]
    pts0, wts0 = np.polynomial.laguerre.laggauss(npts)
    pts = np.sinh(pts0*scl)
    wts = scl*wts0*np.cosh(pts0*scl)*np.exp(pts0)
    return pts, wts

Response: Calculates Gauss - Laguerre quadrature points rescaled for a single line scan.


Instruction:
How would you code a function in Python 3 to
return the wavefront distortion due to z at a given cos_theta and z.

Response:
def f_theta(cos_theta, zint, z, n2n1=0.95, sph6_ab=None, **kwargs):
    """
    Returns the wavefront aberration for an aberrated, defocused lens.

    Calculates the portions of the wavefront distortion due to z, theta
    only, for a lens with defocus and spherical aberration induced by
    coverslip mismatch. (The rho portion can be analytically integrated
    to Bessels.)

    Parameters
    ----------
        cos_theta : numpy.ndarray.
            The N values of cos(theta) at which to compute f_theta.
        zint : Float
            The position of the lens relative to the interface.
        z : numpy.ndarray
            The M z-values to compute f_theta at. `z.size` is unrelated
            to `cos_theta.size`
        n2n1: Float, optional
            The ratio of the index of the immersed medium to the optics.
            Default is 0.95
        sph6_ab : Float or None, optional
            Set sph6_ab to a nonzero value to add residual 6th-order
            spherical aberration that is proportional to sph6_ab. Default
            is None (i.e. doesn't calculate).

    Returns
    -------
        wvfront : numpy.ndarray
            The aberrated wavefront, as a function of theta and z.
            Shape is [z.size, cos_theta.size]
    """
    wvfront = (np.outer(np.ones_like(z)*zint, cos_theta) -
            np.outer(zint+z, csqrt(n2n1**2-1+cos_theta**2)))
    if (sph6_ab is not None) and (not np.isnan(sph6_ab)):
        sec2_theta = 1.0/(cos_theta*cos_theta)
        wvfront += sph6_ab * (sec2_theta-1)*(sec2_theta-2)*cos_theta
    #Ensuring evanescent waves are always suppressed:
    if wvfront.dtype == np.dtype('complex128'):
        wvfront.imag = -np.abs(wvfront.imag)
    return wvfront


Instruction:
Here you have a function in Python 3, explain what it does
def get_Kprefactor(z, cos_theta, zint=100.0, n2n1=0.95, get_hdet=False,
        **kwargs):
    """
    Returns a prefactor in the electric field integral.

    This is an internal function called by get_K. The returned prefactor
    in the integrand is independent of which integral is being called;
    it is a combination of the exp(1j*phase) and apodization.

    Parameters
    ----------
        z : numpy.ndarray
            The values of z (distance along optical axis) at which to
            calculate the prefactor. Size is unrelated to the size of
            `cos_theta`
        cos_theta : numpy.ndarray
            The values of cos(theta) (i.e. position on the incoming
            focal spherical wavefront) at which to calculate the
            prefactor. Size is unrelated to the size of `z`
        zint : Float, optional
            The position of the optical interface, in units of 1/k.
            Default is 100.
        n2n1 : Float, optional
            The ratio of the index mismatch between the optics (n1) and
            the sample (n2). Default is 0.95
        get_hdet : Bool, optional
            Set to True to calculate the detection prefactor vs the
            illumination prefactor (i.e. False to include apodization).
            Default is False

    Returns
    -------
        numpy.ndarray
            The prefactor, of size [`z.size`, `cos_theta.size`], sampled
            at the values [`z`, `cos_theta`]
    """
    phase = f_theta(cos_theta, zint, z, n2n1=n2n1, **kwargs)
    to_return = np.exp(-1j*phase)
    if not get_hdet:
        to_return *= np.outer(np.ones_like(z),np.sqrt(cos_theta))

    return to_return

Response: Calculates the prefactor of the illumination for the given order of the electric field.


Instruction:
Create a Python 3 function for
calculating the symmetric and asymmetric portions of a confocal PSF.

Response:
def get_hsym_asym(rho, z, get_hdet=False, include_K3_det=True, **kwargs):
    """
    Calculates the symmetric and asymmetric portions of a confocal PSF.

    Parameters
    ----------
        rho : numpy.ndarray
            Rho in cylindrical coordinates, in units of 1/k.
        z : numpy.ndarray
            Z in cylindrical coordinates, in units of 1/k. Must be the
            same shape as `rho`
        get_hdet : Bool, optional
            Set to True to get the detection portion of the psf; False
            to get the illumination portion of the psf. Default is True
        include_K3_det : Bool, optional.
            Flag to not calculate the `K3' component for the detection
            PSF, corresponding to (I think) a low-aperature focusing
            lens and no z-polarization of the focused light. Default
            is True, i.e. calculates the K3 component as if the focusing
            lens is high-aperture

    Other Parameters
    ----------------
        alpha : Float, optional
            The acceptance angle of the lens, on (0,pi/2). Default is 1.
        zint : Float, optional
            The distance of the len's unaberrated focal point from the
            optical interface, in units of 1/k. Default is 100.
        n2n1 : Float, optional
            The ratio n2/n1 of the index mismatch between the sample
            (index n2) and the optical train (index n1). Must be on
            [0,inf) but should be near 1. Default is 0.95

    Returns
    -------
        hsym : numpy.ndarray
            `rho`.shape numpy.array of the symmetric portion of the PSF
        hasym : numpy.ndarray
            `rho`.shape numpy.array of the asymmetric portion of the PSF
    """

    K1, Kprefactor = get_K(rho, z, K=1, get_hdet=get_hdet, Kprefactor=None,
            return_Kprefactor=True, **kwargs)
    K2 = get_K(rho, z, K=2, get_hdet=get_hdet, Kprefactor=Kprefactor,
            return_Kprefactor=False, **kwargs)

    if get_hdet and not include_K3_det:
        K3 = 0*K1
    else:
        K3 = get_K(rho, z, K=3, get_hdet=get_hdet, Kprefactor=Kprefactor,
            return_Kprefactor=False, **kwargs)

    hsym = K1*K1.conj() + K2*K2.conj() + 0.5*(K3*K3.conj())
    hasym= K1*K2.conj() + K2*K1.conj() + 0.5*(K3*K3.conj())

    return hsym.real, hasym.real


Instruction:
Create a Python 3 function for
calculating the perfect - pinhole PSF for a set of points x y z.

Response:
def calculate_pinhole_psf(x, y, z, kfki=0.89, zint=100.0, normalize=False,
        **kwargs):
    """
    Calculates the perfect-pinhole PSF, for a set of points (x,y,z).

    Parameters
    -----------
        x : numpy.ndarray
            The x-coordinate of the PSF in units of 1/ the wavevector of
            the incoming light.
        y : numpy.ndarray
            The y-coordinate.
        z : numpy.ndarray
            The z-coordinate.
        kfki : Float
            The (scalar) ratio of wavevectors of the outgoing light to the
            incoming light. Default is 0.89.
        zint : Float
            The (scalar) distance from the interface, in units of
            1/k_incoming. Default is 100.0
        normalize : Bool
            Set to True to normalize the psf correctly, accounting for
            intensity variations with depth. This will give a psf that does
            not sum to 1.

    Other Parameters
    ----------------
        alpha : Float
            The opening angle of the lens. Default is 1.
        n2n1 : Float
            The ratio of the index in the 2nd medium to that in the first.
            Default is 0.95

    Returns
    -------
        psf : numpy.ndarray, of shape x.shape

    Comments
    --------
        (1) The PSF is not necessarily centered on the z=0 pixel, since the
            calculation includes the shift.

        (2) If you want z-varying illumination of the psf then set
            normalize=True. This does the normalization by doing:
                hsym, hasym /= hsym.sum()
                hdet /= hdet.sum()
            and then calculating the psf that way. So if you want the
            intensity to be correct you need to use a large-ish array of
            roughly equally spaced points. Or do it manually by calling
            get_hsym_asym()
    """
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)

    hsym, hasym = get_hsym_asym(rho, z, zint=zint, get_hdet=False, **kwargs)
    hdet, toss  = get_hsym_asym(rho*kfki, z*kfki, zint=kfki*zint, get_hdet=True, **kwargs)

    if normalize:
        hasym /= hsym.sum()
        hsym /= hsym.sum()
        hdet /= hdet.sum()

    return (hsym + np.cos(2*phi)*hasym)*hdet


Instruction:
Create a Python 3 function to
calculate a set of points and weights for a set of polydisp outgoing wavevectors.

Response:
def get_polydisp_pts_wts(kfki, sigkf, dist_type='gaussian', nkpts=3):
    """
    Calculates a set of Gauss quadrature points & weights for polydisperse
    light.

    Returns a list of points and weights of the final wavevector's distri-
    bution, in units of the initial wavevector.

    Parameters
    ----------
        kfki : Float
            The mean of the polydisperse outgoing wavevectors.
        sigkf : Float
            The standard dev. of the polydisperse outgoing wavevectors.
        dist_type : {`gaussian`, `gamma`}, optional
            The distribution, gaussian or gamma, of the wavevectors.
            Default is `gaussian`
        nkpts : Int, optional
            The number of quadrature points to use. Default is 3
    Returns
    -------
        kfkipts : numpy.ndarray
            The Gauss quadrature points at which to calculate kfki.
        wts : numpy.ndarray
            The associated Gauss quadrature weights.
    """
    if dist_type.lower() == 'gaussian':
        pts, wts = np.polynomial.hermite.hermgauss(nkpts)
        kfkipts = np.abs(kfki + sigkf*np.sqrt(2)*pts)
    elif dist_type.lower() == 'laguerre' or dist_type.lower() == 'gamma':
        k_scale = sigkf**2/kfki
        associated_order = kfki**2/sigkf**2 - 1
        #Associated Laguerre with alpha >~170 becomes numerically unstable, so:
        max_order=150
        if associated_order > max_order or associated_order < (-1+1e-3):
            warnings.warn('Numerically unstable sigk, clipping', RuntimeWarning)
            associated_order = np.clip(associated_order, -1+1e-3, max_order)
        kfkipts, wts = la_roots(nkpts, associated_order)
        kfkipts *= k_scale
    else:
        raise ValueError('dist_type must be either gaussian or laguerre')
    return kfkipts, wts/wts.sum()


Instruction:
Write a Python 3 function that can
calculate the PSF for a set of points x y z.

Response:
def calculate_polychrome_pinhole_psf(x, y, z, normalize=False, kfki=0.889,
        sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', **kwargs):
    """
    Calculates the perfect-pinhole PSF, for a set of points (x,y,z).

    Parameters
    -----------
        x : numpy.ndarray
            The x-coordinate of the PSF in units of 1/ the wavevector of
            the incoming light.
        y : numpy.ndarray
            The y-coordinate.
        z : numpy.ndarray
            The z-coordinate.
        kfki : Float
            The mean ratio of the outgoing light's wavevector to the incoming
            light's. Default is 0.89.
        sigkf : Float
            Standard deviation of kfki; the distribution of the light values
            will be approximately kfki +- sigkf.
        zint : Float
            The (scalar) distance from the interface, in units of
            1/k_incoming. Default is 100.0
        dist_type: The distribution type of the polychromatic light.
            Can be one of 'laguerre'/'gamma' or 'gaussian.' If 'gaussian'
            the resulting k-values are taken in absolute value. Default
            is 'gaussian.'
        normalize : Bool
            Set to True to normalize the psf correctly, accounting for
            intensity variations with depth. This will give a psf that does
            not sum to 1. Default is False.

    Other Parameters
    ----------------
        alpha : Float
            The opening angle of the lens. Default is 1.
        n2n1 : Float
            The ratio of the index in the 2nd medium to that in the first.
            Default is 0.95

    Returns
    -------
        psf : numpy.ndarray, of shape x.shape

    Comments
    --------
        (1) The PSF is not necessarily centered on the z=0 pixel, since the
            calculation includes the shift.

        (2) If you want z-varying illumination of the psf then set
            normalize=True. This does the normalization by doing:
                hsym, hasym /= hsym.sum()
                hdet /= hdet.sum()
            and then calculating the psf that way. So if you want the
            intensity to be correct you need to use a large-ish array of
            roughly equally spaced points. Or do it manually by calling
            get_hsym_asym()
    """
    #0. Setup
    kfkipts, wts = get_polydisp_pts_wts(kfki, sigkf, dist_type=dist_type,
            nkpts=nkpts)
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)

    #1. Hilm
    hsym, hasym = get_hsym_asym(rho, z, zint=zint, get_hdet=False, **kwargs)
    hilm = (hsym + np.cos(2*phi)*hasym)

    #2. Hdet
    hdet_func = lambda kfki: get_hsym_asym(rho*kfki, z*kfki,
                zint=kfki*zint, get_hdet=True, **kwargs)[0]
    inner = [wts[a] * hdet_func(kfkipts[a]) for a in range(nkpts)]
    hdet = np.sum(inner, axis=0)

    #3. Normalize and return
    if normalize:
        hilm /= hilm.sum()
        hdet /= hdet.sum()
    psf = hdet * hilm
    return psf if normalize else psf / psf.sum()


Instruction:
Can you tell what is the following Python 3 function doing
def get_psf_scalar(x, y, z, kfki=1., zint=100.0, normalize=False, **kwargs):

    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)

    K1 = get_K(rho, z, K=1,zint=zint,get_hdet=True, **kwargs)
    hilm = np.real( K1*K1.conj() )

    if np.abs(kfki - 1.0) > 1e-13:
        Kdet = get_K(rho*kfki, z*kfki, K=1, zint=zint*kfki, get_hdet=True,
                **kwargs)
        hdet = np.real( Kdet*Kdet.conj() )
    else:
        hdet = hilm.copy()

    if normalize:
        hilm /= hsym.sum()
        hdet /= hdet.sum()
        psf = hilm * hdet
    else:
        psf = hilm * hdet
        # psf /= psf.sum()

    return psf

Response: Calculates the scalar PSF of a specific entry in the system.


Instruction:
Implement a Python 3 function for
calculating the illumination PSF for a line - scanning confocal with the illuminating light.

Response:
def calculate_linescan_ilm_psf(y,z, polar_angle=0., nlpts=1,
        pinhole_width=1, use_laggauss=False, **kwargs):
    """
    Calculates the illumination PSF for a line-scanning confocal with the
    confocal line oriented along the x direction.

    Parameters
    ----------
        y : numpy.ndarray
            The y points (in-plane, perpendicular to the line direction)
            at which to evaluate the illumination PSF, in units of 1/k.
            Arbitrary shape.
        z : numpy.ndarray
            The z points (optical axis) at which to evaluate the illum-
            ination PSF, in units of 1/k. Must be the same shape as `y`
        polar_angle : Float, optional
            The angle of the illuminating light's polarization with
            respect to the line's orientation along x. Default is 0.
        pinhole_width : Float, optional
            The width of the geometric image of the line projected onto
            the sample, in units of 1/k. Default is 1. The perfect line
            image is assumed to be a Gaussian. If `nlpts` is set to 1,
            the line will always be of zero width.
        nlpts : Int, optional
            The number of points to use for Hermite-gauss quadrature over
            the line's width. Default is 1, corresponding to a zero-width
            line.
        use_laggauss : Bool, optional
            Set to True to use a more-accurate sinh'd Laguerre-Gauss
            quadrature for integration over the line's length (more accurate
            in the same amount of time). Default is False for backwards
            compatibility.  FIXME what did we do here?

    Other Parameters
    ----------------
        alpha : Float, optional
            The acceptance angle of the lens, on (0,pi/2). Default is 1.
        zint : Float, optional
            The distance of the len's unaberrated focal point from the
            optical interface, in units of 1/k. Default is 100.
        n2n1 : Float, optional
            The ratio n2/n1 of the index mismatch between the sample
            (index n2) and the optical train (index n1). Must be on
            [0,inf) but should be near 1. Default is 0.95

    Returns
    -------
        hilm : numpy.ndarray
            The line illumination, of the same shape as y and z.
    """
    if use_laggauss:
        x_vals, wts = calc_pts_lag()
    else:
        x_vals, wts = calc_pts_hg()

    #I'm assuming that y,z are already some sort of meshgrid
    xg, yg, zg = [np.zeros( list(y.shape) + [x_vals.size] ) for a in range(3)]
    hilm = np.zeros(xg.shape)

    for a in range(x_vals.size):
        xg[...,a] = x_vals[a]
        yg[...,a] = y.copy()
        zg[...,a] = z.copy()

    y_pinhole, wts_pinhole = np.polynomial.hermite.hermgauss(nlpts)
    y_pinhole *= np.sqrt(2)*pinhole_width
    wts_pinhole /= np.sqrt(np.pi)

    #Pinhole hermgauss first:
    for yp, wp in zip(y_pinhole, wts_pinhole):
        rho = np.sqrt(xg*xg + (yg-yp)*(yg-yp))
        phi = np.arctan2(yg,xg)

        hsym, hasym = get_hsym_asym(rho,zg,get_hdet = False, **kwargs)
        hilm += wp*(hsym + np.cos(2*(phi-polar_angle))*hasym)

    #Now line hermgauss
    for a in range(x_vals.size):
        hilm[...,a] *= wts[a]

    return hilm.sum(axis=-1)*2.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calculate_linescan_psf(x, y, z, normalize=False, kfki=0.889, zint=100.,
        polar_angle=0., wrap=True, **kwargs):
    """
    Calculates the point spread function of a line-scanning confocal.

    Make x,y,z  __1D__ numpy.arrays, with x the direction along the
    scan line. (to make the calculation faster since I dont' need the line
    ilm for each x).

    Parameters
    ----------
        x : numpy.ndarray
            _One_dimensional_ array of the x grid points (along the line
            illumination) at which to evaluate the psf. In units of
            1/k_incoming.
        y : numpy.ndarray
            _One_dimensional_ array of the y grid points (in plane,
            perpendicular to the line illumination) at which to evaluate
            the psf. In units of 1/k_incoming.
        z : numpy.ndarray
            _One_dimensional_ array of the z grid points (along the
            optical axis) at which to evaluate the psf. In units of
            1/k_incoming.
        normalize : Bool, optional
            Set to True to include the effects of PSF normalization on
            the image intensity. Default is False.
        kfki : Float, optional
            The ratio of the final light's wavevector to the incoming.
            Default is 0.889
        zint : Float, optional
            The position of the optical interface, in units of 1/k_incoming
            Default is 100.
        wrap : Bool, optional
            If True, wraps the psf calculation for speed, assuming that
            the input x, y are regularly-spaced points. If x,y are not
            regularly spaced then `wrap` must be set to False. Default is True.
        polar_angle : Float, optional
            The polarization angle of the light (radians) with respect to
            the line direction (x). Default is 0.

    Other Parameters
    ----------------
        alpha : Float
            The opening angle of the lens. Default is 1.
        n2n1 : Float
            The ratio of the index in the 2nd medium to that in the first.
            Default is 0.95

    Returns
    -------
        numpy.ndarray
            A 3D- numpy.array of the point-spread function. Indexing is
            psf[x,y,z]; shape is [x.size, y,size, z.size]
    """

    #0. Set up vecs
    if wrap:
        xpts = vec_to_halfvec(x)
        ypts = vec_to_halfvec(y)
        x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')
    else:
        x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')
    rho3 = np.sqrt(x3*x3 + y3*y3)

    #1. Hilm
    if wrap:
        y2,z2 = np.meshgrid(ypts, z, indexing='ij')
        hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint,
                polar_angle=polar_angle, **kwargs)
        if ypts[0] == 0:
            hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)
        else:
            hilm = np.append(hilm0[::-1], hilm0, axis=0)
    else:
        y2,z2 = np.meshgrid(y, z, indexing='ij')
        hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint,
                polar_angle=polar_angle, **kwargs)

    #2. Hdet
    if wrap:
        #Lambda function that ignores its args but still returns correct values
        func = lambda *args: get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,
                    get_hdet=True, **kwargs)[0]
        hdet = wrap_and_calc_psf(xpts, ypts, z, func)
    else:
        hdet, toss = get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,
                get_hdet=True, **kwargs)

    if normalize:
        hilm /= hilm.sum()
        hdet /= hdet.sum()

    for a in range(x.size):
        hdet[a] *= hilm

    return hdet if normalize else hdet / hdet.sum()

Response: Calculates the point spread function of a line - scanning confocal.


Instruction:
Here you have a function in Python 3, explain what it does
def calculate_polychrome_linescan_psf(x, y, z, normalize=False, kfki=0.889,
        sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', wrap=True,
        **kwargs):
    """
    Calculates the point spread function of a line-scanning confocal with
    polydisperse dye emission.

    Make x,y,z  __1D__ numpy.arrays, with x the direction along the
    scan line. (to make the calculation faster since I dont' need the line
    ilm for each x).

    Parameters
    ----------
        x : numpy.ndarray
            _One_dimensional_ array of the x grid points (along the line
            illumination) at which to evaluate the psf. In units of
            1/k_incoming.
        y : numpy.ndarray
            _One_dimensional_ array of the y grid points (in plane,
            perpendicular to the line illumination) at which to evaluate
            the psf. In units of 1/k_incoming.
        z : numpy.ndarray
            _One_dimensional_ array of the z grid points (along the
            optical axis) at which to evaluate the psf. In units of
            1/k_incoming.
        normalize : Bool, optional
            Set to True to include the effects of PSF normalization on
            the image intensity. Default is False.
        kfki : Float, optional
            The mean of the ratio of the final light's wavevector to the
            incoming. Default is 0.889
        sigkf : Float, optional
            The standard deviation of the ratio of the final light's
            wavevector to the incoming. Default is 0.1
        zint : Float, optional
            The position of the optical interface, in units of 1/k_incoming
            Default is 100.
        dist_type : {`gaussian`, `gamma`}, optional
            The distribution of the outgoing light. If 'gaussian' the
            resulting k-values are taken in absolute value. Default
            is `gaussian`
        wrap : Bool, optional
            If True, wraps the psf calculation for speed, assuming that
            the input x, y are regularly-spaced points. If x,y are not
            regularly spaced then `wrap` must be set to False. Default is True.

    Other Parameters
    ----------------
        polar_angle : Float, optional
            The polarization angle of the light (radians) with respect to
            the line direction (x). Default is 0.
        alpha : Float
            The opening angle of the lens. Default is 1.
        n2n1 : Float
            The ratio of the index in the 2nd medium to that in the first.
            Default is 0.95

    Returns
    -------
        numpy.ndarray
            A 3D- numpy.array of the point-spread function. Indexing is
            psf[x,y,z]; shape is [x.size, y,size, z.size]
    Notes
    -----
        Neither distribution type is perfect. If sigkf/k0 is big (>0.5ish)
        then part of the Gaussian is negative. To avoid issues an abs() is
        taken, but then the actual mean and variance are not what is
        supplied. Conversely, if sigkf/k0 is small (<0.0815), then the
        requisite associated Laguerre quadrature becomes unstable. To
        prevent this sigkf/k0 is effectively clipped to be > 0.0815.
    """
    kfkipts, wts = get_polydisp_pts_wts(kfki, sigkf, dist_type=dist_type,
            nkpts=nkpts)

    #0. Set up vecs
    if wrap:
        xpts = vec_to_halfvec(x)
        ypts = vec_to_halfvec(y)
        x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')
    else:
        x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')
    rho3 = np.sqrt(x3*x3 + y3*y3)

    #1. Hilm
    if wrap:
        y2,z2 = np.meshgrid(ypts, z, indexing='ij')
        hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)
        if ypts[0] == 0:
            hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)
        else:
            hilm = np.append(hilm0[::-1], hilm0, axis=0)
    else:
        y2,z2 = np.meshgrid(y, z, indexing='ij')
        hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)

    #2. Hdet
    if wrap:
        #Lambda function that ignores its args but still returns correct values
        func = lambda x,y,z, kfki=1.: get_hsym_asym(rho3*kfki, z3*kfki,
                zint=kfki*zint, get_hdet=True, **kwargs)[0]
        hdet_func = lambda kfki: wrap_and_calc_psf(xpts,ypts,z, func, kfki=kfki)
    else:
        hdet_func = lambda kfki: get_hsym_asym(rho3*kfki, z3*kfki,
                zint=kfki*zint, get_hdet=True, **kwargs)[0]
    #####
    inner = [wts[a] * hdet_func(kfkipts[a]) for a in range(nkpts)]
    hdet = np.sum(inner, axis=0)

    if normalize:
        hilm /= hilm.sum()
        hdet /= hdet.sum()
    for a in range(x.size):
        hdet[a] *= hilm

    return hdet if normalize else hdet / hdet.sum()

Response: Calculates the point spread function of a line - scanning confocal with a poly - chrome line - scanning confocal with a single line - scanning system.


Instruction:
Write a Python 3 function that can
wrap a point - spread function in x and y and z and return a numpy array of the wrapped and calculated psf.

Response:
def wrap_and_calc_psf(xpts, ypts, zpts, func, **kwargs):
    """
    Wraps a point-spread function in x and y.

    Speeds up psf calculations by a factor of 4 for free / some broadcasting
    by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y
    as the positive (say) values of the coordinates at which to evaluate func,
    and it will return the function sampled at [x[::-1]] + x. Note it is not
    wrapped in z.

    Parameters
    ----------
        xpts : numpy.ndarray
            1D N-element numpy.array of the x-points to evaluate func at.
        ypts : numpy.ndarray
            y-points to evaluate func at.
        zpts : numpy.ndarray
            z-points to evaluate func at.
        func : function
            The function to evaluate and wrap around. Syntax must be
            func(x,y,z, **kwargs)
        **kwargs : Any parameters passed to the function.

    Outputs
    -------
        to_return : numpy.ndarray
            The wrapped and calculated psf, of shape
            [2*x.size - x0, 2*y.size - y0, z.size], where x0=1 if x[0]=0, etc.

    Notes
    -----
    The coordinates should be something like numpy.arange(start, stop, diff),
    with start near 0. If x[0]==0, all of x is calcualted but only x[1:]
    is wrapped (i.e. it works whether or not x[0]=0).

    This doesn't work directly for a linescan psf because the illumination
    portion is not like a grid. However, the illumination and detection
    are already combined with wrap_and_calc in calculate_linescan_psf etc.
    """
    #1. Checking that everything is hunky-dory:
    for t in [xpts,ypts,zpts]:
        if len(t.shape) != 1:
            raise ValueError('xpts,ypts,zpts must be 1D.')

    dx = 1 if xpts[0]==0 else 0
    dy = 1 if ypts[0]==0 else 0

    xg,yg,zg = np.meshgrid(xpts,ypts,zpts, indexing='ij')
    xs, ys, zs = [ pts.size for pts in [xpts,ypts,zpts] ]
    to_return = np.zeros([2*xs-dx, 2*ys-dy, zs])

    #2. Calculate:
    up_corner_psf = func(xg,yg,zg, **kwargs)

    to_return[xs-dx:,ys-dy:,:] = up_corner_psf.copy()                     #x>0, y>0
    if dx == 0:
        to_return[:xs-dx,ys-dy:,:] = up_corner_psf[::-1,:,:].copy()       #x<0, y>0
    else:
        to_return[:xs-dx,ys-dy:,:] = up_corner_psf[-1:0:-1,:,:].copy()    #x<0, y>0
    if dy == 0:
        to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,::-1,:].copy()       #x>0, y<0
    else:
        to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,-1:0:-1,:].copy()    #x>0, y<0
    if (dx == 0) and (dy == 0):
        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,::-1,:].copy()    #x<0,y<0
    elif (dx == 0) and (dy != 0):
        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,-1:0:-1,:].copy() #x<0,y<0
    elif (dy == 0) and (dx != 0):
        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,::-1,:].copy() #x<0,y<0
    else: #dx==1 and dy==1
        to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,-1:0:-1,:].copy()#x<0,y<0

    return to_return


Instruction:
Can you create a Python 3 function that
transforms a vector np. arange - N M dx to np. arange - N M dx

Response:
def vec_to_halfvec(vec):
    """Transforms a vector np.arange(-N, M, dx) to np.arange(min(|vec|), max(N,M),dx)]"""
    d = vec[1:] - vec[:-1]
    if ((d/d.mean()).std() > 1e-14) or (d.mean() < 0):
        raise ValueError('vec must be np.arange() in increasing order')
    dx = d.mean()
    lowest = np.abs(vec).min()
    highest = np.abs(vec).max()
    return np.arange(lowest, highest + 0.1*dx, dx).astype(vec.dtype)


Instruction:
Create a Python 3 function for
converting a scalar a to a list and all iterables to list as well.

Response:
def listify(a):
    """
    Convert a scalar ``a`` to a list and all iterables to list as well.

    Examples
    --------
    >>> listify(0)
    [0]

    >>> listify([1,2,3])
    [1, 2, 3]

    >>> listify('a')
    ['a']

    >>> listify(np.array([1,2,3]))
    [1, 2, 3]

    >>> listify('string')
    ['string']
    """
    if a is None:
        return []
    elif not isinstance(a, (tuple, list, np.ndarray)):
        return [a]
    return list(a)


Instruction:
Write a Python 3 function that can
return a list of objects that are not in a single element list.

Response:
def delistify(a, b=None):
    """
    If a single element list, extract the element as an object, otherwise
    leave as it is.

    Examples
    --------
    >>> delistify('string')
    'string'

    >>> delistify(['string'])
    'string'

    >>> delistify(['string', 'other'])
    ['string', 'other']

    >>> delistify(np.array([1.0]))
    1.0

    >>> delistify([1, 2, 3])
    [1, 2, 3]
    """
    if isinstance(b, (tuple, list, np.ndarray)):
        if isinstance(a, (tuple, list, np.ndarray)):
            return type(b)(a)
        return type(b)([a])
    else:
        if isinstance(a, (tuple, list, np.ndarray)) and len(a) == 1:
            return a[0]
        return a
    return a


Instruction:
Given the following Python 3 function, write the documentation
def aN(a, dim=3, dtype='int'):
    if not hasattr(a, '__iter__'):
        return np.array([a]*dim, dtype=dtype)
    return np.array(a).astype(dtype)

Response: Convert an integer or iterable list to numpy array of length dim.


Instruction:
Explain what the following Python 3 code does
def cdd(d, k):
    if not isinstance(k, list):
        k = [k]
    for i in k:
        if i in d:
            d.pop(i)

Response: Conditionally delete key or list of keys from dict d


Instruction:
Can you generate a brief explanation for the following Python 3 code
def patch_docs(subclass, superclass):
    funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)
    funcs1 = inspect.getmembers(superclass, predicate=inspect.ismethod)

    funcs1 = [f[0] for f in funcs1]

    for name, func in funcs0:
        if name.startswith('_'):
            continue

        if name not in funcs1:
            continue

        if func.__doc__ is None:
            func = getattr(subclass, name)
            func.__func__.__doc__ = getattr(superclass, name).__func__.__doc__

Response:
Apply the documentation from subclass to superclass by filling the documentation from all overridden member function docstrings with those from the
    parent class


Instruction:
Can you generate the documentation for the following Python 3 function
def indir(path):
    cwd = os.getcwd()

    try:
        os.chdir(path)
        yield
    except Exception as e:
        raise
    finally:
        os.chdir(cwd)

Response: Context manager for switching the current path of the process.


Instruction:
How would you implement a function in Python 3 that
arrays slicer object for this tile

Response:
def slicer(self):
        """
        Array slicer object for this tile

        >>> Tile((2,3)).slicer
        (slice(0, 2, None), slice(0, 3, None))

        >>> np.arange(10)[Tile((4,)).slicer]
        array([0, 1, 2, 3])
        """
        return tuple(np.s_[l:r] for l,r in zip(*self.bounds))


Instruction:
Explain what the following Python 3 code does
def oslicer(self, tile):
        mask = None
        vecs = tile.coords(form='meshed')
        for v in vecs:
            v[self.slicer] = -1
            mask = mask & (v > 0) if mask is not None else (v>0)
        return tuple(np.array(i).astype('int') for i in zip(*[v[mask] for v in vecs]))

Response: Opposite slicer the outer part wrt to a field


Instruction:
Can you generate a brief explanation for the following Python 3 code
def kcenter(self):
        return np.array([
            np.abs(np.fft.fftshift(np.fft.fftfreq(q))).argmin()
            for q in self.shape
        ]).astype('float')

Response: Return the frequency center of the tile


Instruction:
Can you tell what is the following Python 3 function doing
def corners(self):
        corners = []
        for ind in itertools.product(*((0,1),)*self.dim):
            ind = np.array(ind)
            corners.append(self.l + ind*self.r)
        return np.array(corners)

Response: Iterate the vector of all corners of the hyperrectangles


Instruction:
How would you implement a function in Python 3 that
formats a 3d vector field in certain ways see coords for a description of each formatting method.

Response:
def _format_vector(self, vecs, form='broadcast'):
        """
        Format a 3d vector field in certain ways, see `coords` for a description
        of each formatting method.
        """
        if form == 'meshed':
            return np.meshgrid(*vecs, indexing='ij')
        elif form == 'vector':
            vecs = np.meshgrid(*vecs, indexing='ij')
            return np.rollaxis(np.array(np.broadcast_arrays(*vecs)),0,self.dim+1)
        elif form == 'flat':
            return vecs
        else:
            return [v[self._coord_slicers[i]] for i,v in enumerate(vecs)]


Instruction:
Make a summary of the following Python 3 code
def coords(self, norm=False, form='broadcast'):
        if norm is False:
            norm = 1
        if norm is True:
            norm = np.array(self.shape)
        norm = aN(norm, self.dim, dtype='float')

        v = list(np.arange(self.l[i], self.r[i]) / norm[i] for i in range(self.dim))
        return self._format_vector(v, form=form)

Response: Returns the coordinates of the tile.


Instruction:
How would you explain what the following Python 3 function does
def kvectors(self, norm=False, form='broadcast', real=False, shift=False):
        if norm is False:
            norm = 1
        if norm is True:
            norm = np.array(self.shape)
        norm = aN(norm, self.dim, dtype='float')

        v = list(np.fft.fftfreq(self.shape[i])/norm[i] for i in range(self.dim))

        if shift:
            v = list(np.fft.fftshift(t) for t in v)

        if real:
            v[-1] = v[-1][:(self.shape[-1]+1)//2]

        return self._format_vector(v, form=form)

Response: Return the kvectors associated with this tile.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def contains(self, items, pad=0):
        o = ((items >= self.l-pad) & (items < self.r+pad))
        if len(o.shape) == 2:
            o = o.all(axis=-1)
        elif len(o.shape) == 1:
            o = o.all()
        return o

Response: Test whether the given items are contained within this tile.


Instruction:
Write a Python 3 function for
translating a tile by an amount dr

Response:
def translate(self, dr):
        """
        Translate a tile by an amount dr

        >>> Tile(5).translate(1)
        Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])
        """
        tile = self.copy()
        tile.l += dr
        tile.r += dr
        return tile


Instruction:
Write a Python 3 script for
padding this tile by an equal amount on each side as specified by pad

Response:
def pad(self, pad):
        """
        Pad this tile by an equal amount on each side as specified by pad

        >>> Tile(10).pad(2)
        Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])

        >>> Tile(10).pad([1,2,3])
        Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])
        """
        tile = self.copy()
        tile.l -= pad
        tile.r += pad
        return tile


Instruction:
How would you explain what the following Python 3 function does
def overhang(self, tile):
        ll = np.abs(amin(self.l - tile.l, aN(0, dim=self.dim)))
        rr = np.abs(amax(self.r - tile.r, aN(0, dim=self.dim)))
        return ll, rr

Response: Get the left and right absolute overflow of a given tile


Instruction:
Can you generate the documentation for the following Python 3 function
def reflect_overhang(self, clip):
        orig = self.copy()
        tile = self.copy()

        hangl, hangr = tile.overhang(clip)
        tile = tile.pad(hangl)
        tile = tile.pad(hangr)

        inner = Tile.intersection([clip, orig])
        outer = Tile.intersection([clip, tile])
        return inner, outer

Response:
Compute the overhang and reflect it internally so respect periodic
        padding rules. Returns both the inner tile and the outer tile with necessary pad.


Instruction:
Create a Python 3 function for
returning a filtered image after applying the Fourier - space filters

Response:
def filtered_image(self, im):
        """Returns a filtered image after applying the Fourier-space filters"""
        q = np.fft.fftn(im)
        for k,v in self.filters:
            q[k] -= v
        return np.real(np.fft.ifftn(q))


Instruction:
Can you generate the documentation for the following Python 3 function
def set_filter(self, slices, values):
        self.filters = [[sl,values[sl]] for sl in slices]

Response: Sets the Fourier - space filters for the image.


Instruction:
Can you implement a function in Python 3 that
loads the image from the file and perform any transforms to get a loaded image

Response:
def load_image(self):
        """ Read the file and perform any transforms to get a loaded image """
        try:
            image = initializers.load_tiff(self.filename)
            image = initializers.normalize(
                image, invert=self.invert, scale=self.exposure,
                dtype=self.float_precision
            )
        except IOError as e:
            log.error("Could not find image '%s'" % self.filename)
            raise e

        return image


Instruction:
Can you write a function in Python 3 where it
returns the minimum and maximum of the image in this object.

Response:
def get_scale(self):
        """
        If exposure was not set in the __init__, get the exposure associated
        with this RawImage so that it may be used in other
        :class:`~peri.util.RawImage`. This is useful for transferring exposure
        parameters to a series of images.

        Returns
        -------
        exposure : tuple of floats
            The (emin, emax) which get mapped to (0, 1)
        """
        if self.exposure is not None:
            return self.exposure

        raw = initializers.load_tiff(self.filename)
        return raw.min(), raw.max()


Instruction:
How would you explain what the following Python 3 function does
def get_scale_from_raw(raw, scaled):
        t0, t1 = scaled.min(), scaled.max()
        r0, r1 = float(raw.min()), float(raw.max())

        rmin = (t1*r0 - t0*r1) / (t1 - t0)
        rmax = (r1 - r0) / (t1 - t0) + rmin
        return (rmin, rmax)

Response: This function takes a raw image and a scaled version of the same image and returns the exposure parameters associated with those images.


Instruction:
Make a summary of the following Python 3 code
def update(self, value=0):
        self._deltas.append(time.time())

        self.value = value
        self._percent = 100.0 * self.value / self.num

        if self.bar:
            self._bars = self._bar_symbol*int(np.round(self._percent / 100. * self._barsize))

        if (len(self._deltas) < 2) or (self._deltas[-1] - self._deltas[-2]) > 1e-1:
            self._estimate_time()
            self._draw()

        if self.value == self.num:
            self.end()

Response: Update the value of the progress and update the progress bar.


Instruction:
Can you write a function in Python 3 where it
checks that the modelstr and varmap are consistent across the many components.

Response:
def check_consistency(self):
        """
        Make sure that the required comps are included in the list of
        components supplied by the user. Also check that the parameters are
        consistent across the many components.
        """
        error = False
        regex = re.compile('([a-zA-Z_][a-zA-Z0-9_]*)')

        # there at least must be the full model, not necessarily partial updates
        if 'full' not in self.modelstr:
            raise ModelError(
                'Model must contain a `full` key describing '
                'the entire image formation'
            )

        # Check that the two model descriptors are consistent
        for name, eq in iteritems(self.modelstr):
            var = regex.findall(eq)
            for v in var:
                # remove the derivative signs if there (dP -> P)
                v = re.sub(r"^d", '', v)
                if v not in self.varmap:
                    log.error(
                        "Variable '%s' (eq. '%s': '%s') not found in category map %r" %
                        (v, name, eq, self.varmap)
                    )
                    error = True

        if error:
            raise ModelError('Inconsistent varmap and modelstr descriptions')


Instruction:
Here you have a function in Python 3, explain what it does
def check_inputs(self, comps):
        error = False
        compcats = [c.category for c in comps]

        # Check that the components are all provided, given the categories
        for k, v in iteritems(self.varmap):
            if k not in self.modelstr['full']:
                log.warn('Component (%s : %s) not used in model.' % (k,v))

            if v not in compcats:
                log.error('Map component (%s : %s) not found in list of components.' % (k,v))
                error = True

        if error:
            raise ModelError('Component list incomplete or incorrect')

Response: Check that the list of components comp is compatible with both the varmap and modelstr for this Model


Instruction:
Can you implement a function in Python 3 that
gets the model corresponding to a variation wrt a category. For example is H + B.

Response:
def get_difference_model(self, category):
        """
        Get the equation corresponding to a variation wrt category. For example
        if::

            modelstr = {
                'full' :'H(I) + B',
                'dH' : 'dH(I)',
                'dI' : 'H(dI)',
                'dB' : 'dB'
            }

            varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'}

        then ``get_difference_model('obj') == modelstr['dI'] == 'H(dI)'``
        """
        name = self.diffname(self.ivarmap[category])
        return self.modelstr.get(name)


Instruction:
Write a Python 3 script for
mapping component function funcname result into model variables dictionary for use in eval of the model.

Response:
def map_vars(self, comps, funcname='get', diffmap=None, **kwargs):
        """
        Map component function ``funcname`` result into model variables
        dictionary for use in eval of the model. If ``diffmap`` is provided then
        that symbol is translated into 'd'+diffmap.key and is replaced by
        diffmap.value. ``**kwargs` are passed to the ``comp.funcname(**kwargs)``.
        """
        out = {}
        diffmap = diffmap or {}

        for c in comps:
            cat = c.category

            if cat in diffmap:
                symbol = self.diffname(self.ivarmap[cat])
                out[symbol] = diffmap[cat]
            else:
                symbol = self.ivarmap[cat]
                out[symbol] = getattr(c, funcname)(**kwargs)

        return out


Instruction:
Can you generate the documentation for the following Python 3 function
def evaluate(self, comps, funcname='get', diffmap=None, **kwargs):
        evar = self.map_vars(comps, funcname, diffmap=diffmap)

        if diffmap is None:
            return eval(self.get_base_model(), evar)
        else:
            compname = list(diffmap.keys())[0]
            return eval(self.get_difference_model(compname), evar)

Response: Evaluate the model of a set of components and return the output of a model.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def lbl(axis, label, size=22):
    at = AnchoredText(label, loc=2, prop=dict(size=size), frameon=True)
    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.0")
    #bb = axis.get_yaxis_transform()
    #at = AnchoredText(label,
    #        loc=3, prop=dict(size=18), frameon=True,
    #        bbox_to_anchor=(-0.5,1),#(-.255, 0.90),
    #        bbox_transform=bb,#axis.transAxes
    #    )
    axis.add_artist(at)

Response: Put a figure label in an axis