import numpy as np
import torch
from torch.autograd import grad

from pyrosetta import *
from rosetta.core.scoring.methods import \
  ContextIndependentOneBodyEnergy, LongRangeTwoBodyEnergy
from rosetta.core.scoring import ScoreType

from betafold.distributions.von_mises import TorsionDistribution

@rosetta.EnergyMethod
class DistanceTerm(LongRangeTwoBodyEnergy):
  def __init__(self, distogram, reference_distogram,
               min_distance=2, max_distance=22, bins=64):
    LongRangeTwoBodyEnergy.__init__(self, self.creator())
    self.distogram = distogram
    self.reference = reference_distogram
    self.min_distance = min_distance
    self.max_distance = max_distance
    self.bins = bins

  def _bin_distance(self, distance):
    numerator = distance - self.min_distance + 1e-6
    denominator = self.max_distance - self.min_distance + 1e-6
    return int(numerator / denominator * self.bins)

  def residue_pair_energy(self, res1, res2, pose, sf, emap):
    cb1 = res1.atom(res1.atom_index("CB")).xyz
    cb2 = res2.atom(res2.atom_index("CB")).xyz
    pos1 = res1.seqpos() - 1
    pos2 = res2.seqpos() - 1
    distance = (cb2 - cb1).norm()
    logit_bin = self._bin_distance(distance)
    numerator = self.reference[pos1, pos2, logit_bin]
    denominator = self.distogram[pos1, pos2, logit_bin]
    score = numerator - denominator
    emap.get().set(self.scoreType, score)

@rosetta.EnergyMethod
class InterpolatedDistanceTerm(DistanceTerm):
  def __init__(self, distogram, reference_distogram, min_distance=2, max_distance=22, bins=64):
    DistanceTerm.__init__(self, distogram, reference_distogram,
                          min_distance=min_distance,
                          max_distance=max_distance,
                          bins=bins)

  def _debin_distance(self, bin_id):
    distance = bin_id / self.bins * self.max_distance
    return distance

  def _interpolate(self, x, y, distance):
    if not isinstance(distance, torch.Tensor):
      distance = torch.tensor(distance)

    distance_bin = self._bin_distance(distance)
    distance_next = (distance_bin + 1) % self.bins
    distance_offset = self._debin_distance(distance_bin)
    distance_p = (distance - distance_offset) / self.max_distance * self.bins % 1
    if self.has_ref:
      numerators = torch.Tensor([
        self.reference[distance_bin, x, y],
        self.reference[distance_next, x, y]
      ])
    else:
      numerators = torch.zeros(2)
    denominators = torch.Tensor([
      self.distogram[distance_bin, x, y],
      self.distogram[distance_next, x, y]
    ])
    score_points = numerators - denominators
    score = score_points[0] * (1 - distance_p) + score_points[1] * distance_p
    return score

  def residue_pair_energy(self, res1, res2, pose, sf, emap):
    cb1 = res1.atom(res1.atom_index("CB")).xyz
    cb2 = res2.atom(res2.atom_index("CB")).xyz
    pos1 = res1.seqpos() - 1
    pos2 = res2.seqpos() - 1
    distance = (cb2 - cb1).norm()
    score = self._interpolate(pos1, pos2, distance)
    emap.get().set(self.scoreType, score)

  def _internal_distance_derivative(self, x, y):
    f2 = x - y
    distance = f2.length()
    if distance != 0.0:
      invd = 1 / distance
      f1 = x.cross(y)
      f1 *= invd
      f2 *= invd
    else:
      f1 = 0.0
    return f1, f2, distance

  def eval_residue_atom_derivative(self, atom_id, pose, dm, scorefxn, weights, f1, f2):
    pos1 = atom_id.rsd()
    x = pose.conformation().xyz(atom_id)
    for pos2 in range(pose.total_residue()):
      y = pose.conformation().xyz(rosetta.core.id.AtomID(atom_id.atomno(), pos2))
      r1, r2, distance = self._internal_distance_derivative(x, y)
      distance = torch.tensor(distance, requires_grad=True)
      score = self._interpolate(pos1, pos2, distance)
      gradient = grad([score], [distance])[0]
      r1 *= float(gradient)
      r2 *= float(gradient)
      f1 += r1
      f2 += r2

@rosetta.EnergyMethod
class TorsionTerm(ContextIndependentOneBodyEnergy):
  def __init__(self, torsion, reference_torsion=None, bins=36):
    ContextIndependentOneBodyEnergy.__init__(self, self.creator())
    self.torsion = torsion
    self.reference = None
    self.has_ref = True
    if reference_torsion is None:
      self.has_ref = False
    else:
      self.reference = reference_torsion
    self.bins = bins

  def _bin_angle(self, angle):
    angle_bin = int((angle + 180) / 360 * self.bins)
    return angle_bin

  def residue_energy(self, res, pose, emap):
    pos = res.seqpos()
    phi = pose.phi(pos)
    psi = pose.psi(pos)
    phi_bin = self._bin_angle(phi)
    psi_bin = self._bin_angle(psi)
    if self.has_ref:
      numerator = self.reference[pos, phi_bin, psi_bin]
    else:
      numerator = 0.0
    denominator = self.torsion[pos, phi_bin, psi_bin]
    score = numerator - denominator
    emap.get().set(self.scoreType, score)

@rosetta.EnergyMethod
class SmoothTorsionTerm(TorsionTerm):
  def __init__(self, torsion, reference_torsion=None, bins=36,
               concentration=1 / ((np.pi / 18) ** 2)):
    TorsionTerm.__init__(self, torsion, reference_torsion, bins=bins)
    space = np.linspace(-180, 180, bins)
    self.mu = np.repeat(space, bins)
    self.nu = np.repeat(space.reshape(bins, 1), bins, axis=1).reshape(-1)
    self.weights = torch.softmax(
      self.torsion.reshape(self.torsion.size(0), -1),
      dim=1
    )
    self.k = concentration

  def _residue_logprob(self, pos, phi, psi):
    if not isinstance(phi, torch.Tensor):
      phi = torch.tensor(phi)
    if not isinstance(psi, torch.Tensor):
      psi = torch.tensor(psi)
    distribution = TorsionDistribution(
      self.mu, self.nu, self.weights[pos],
      k1=self.k, k2=self.k
    )
    return distribution.log_density(phi, psi)

  def residue_energy(self, res, pose, emap):
    pos = res.seqpos()
    phi = res.mainchain_torsion(1)
    psi = res.mainchain_torsion(2)
    return self._residue_logprob(pos, phi, psi)

  def defines_dof_derivatives(self, pose):
    return True

  def eval_residue_dof_derivative(self, res, min_data, dof_id, torsion_id, pose, sfxn, weights):
    if not torsion_id.valid() or torsion_id.type() != rosetta.core.id.TorsionType.BB:
      return 0.0

    phi = torch.tensor(res.mainchain_torsion(1), requires_grad=True)
    psi = torch.tensor(res.mainchain_torsion(2), requires_grad=True)
    prob = self._residue_logprob(phi, psi)
    gradients = grad([prob], [phi, psi])
    return float(gradients[torsion_id.torsion() - 1])

  def eval_dof_derivative(self, dof_id, torsion_id, pose, sfxn, weights):
    res = pose.residue(torsion_id.rsd())
    if not torsion_id.valid() or torsion_id.type() != rosetta.core.id.TorsionType.BB:
      return 0.0

    phi = torch.tensor(res.mainchain_torsion(1), requires_grad=True)
    psi = torch.tensor(res.mainchain_torsion(2), requires_grad=True)
    prob = self._residue_logprob(phi, psi)
    gradients = grad([prob], [phi, psi])
    return float(gradients[torsion_id.torsion() - 1])

@rosetta.EnergyMethod
class SmoothArgmaxTorsionTerm(SmoothTorsionTerm):
  def __init__(self, torsion, reference_torsion=None, bins=36,
               concentration=1 / ((np.pi / 18) ** 2)):
    SmoothTorsionTerm.__init__(self, torsion, reference_torsion, bins=bins)
    self.weights = None
    self.k = concentration
    torsion_max = self.torsion.reshape(
      self.torsion.size(0), -1
    ).argmax(dim=1)
    self.mu = torsion_max % bins
    self.nu = torsion_max // bins

  def _residue_logprob(self, pos, phi, psi):
    if not isinstance(phi, torch.Tensor):
      phi = torch.tensor(phi)
    if not isinstance(psi, torch.Tensor):
      psi = torch.tensor(psi)
    distribution = TorsionDistribution(
      self.mu[pos], self.nu[pos],
      k1=self.k, k2=self.k
    )
    return distribution.log_density(phi, psi)

@rosetta.EnergyMethod
class InterpolatedTorsionTerm(TorsionTerm):
  def __init__(self, torsion, reference_torsion, bins=36, ):
    TorsionTerm.__init__(self, torsion, reference_torsion, bins=bins)

  def _debin_angle(self, bin_id):
    angle = bin_id / self.bins * 360 - 180
    return angle

  def _interpolate(self, pos, phi, psi):
    if not isinstance(phi, torch.Tensor):
      phi = torch.tensor(phi)
    if not isinstance(psi, torch.Tensor):
      psi = torch.tensor(psi)

    phi_bin = self._bin_angle(phi)
    phi_next = (phi_bin + 1) % self.bins
    psi_bin = self._bin_angle(psi)
    psi_next = (psi_bin + 1) % self.bins
    phi_offset = self._debin_angle(phi_bin)
    psi_offset = self._debin_angle(psi_bin)
    phi_p = (phi - phi_offset) / 360 * self.bins % 1
    psi_p = (psi - psi_offset) / 360 * self.bins % 1
    if self.has_ref:
      numerators = torch.Tensor([
        [self.reference[pos, phi_bin, psi_bin], self.reference[pos, phi_next, psi_bin]],
        [self.reference[pos, phi_bin, psi_next], self.reference[pos, phi_next, psi_next]]
      ])
    else:
      numerators = torch.zeros(2, 2)
    denominators = torch.Tensor([
      [self.torsion[pos, phi_bin, psi_bin], self.torsion[pos, phi_next, psi_bin]],
      [self.torsion[pos, phi_bin, psi_next], self.torsion[pos, phi_next, psi_next]]
    ])
    score_points = numerators - denominators
    score = score_points[0, 0] * (1 - phi_p) * (1 - psi_p) \
          + score_points[1, 0] * phi_p * (1 - psi_p) \
          + score_points[0, 1] * (1 - phi_p) * psi_p \
          + score_points[1, 1] * phi_p * psi_p
    return score

  def residue_energy(self, res, pose, emap):
    pos = res.seqpos()
    phi = res.mainchain_torsion(1)
    psi = res.mainchain_torsion(2)
    score = self._interpolate(pos, phi, psi)
    emap.get().set(self.scoreType, score)

  def defines_dof_derivatives(self, pose):
    return True

  def eval_residue_dof_derivative(self, res, min_data, dof_id, torsion_id, pose, sfxn, weights):
    if not torsion_id.valid() or torsion_id.type() != rosetta.core.id.TorsionType.BB:
      return 0.0

    phi = torch.tensor(res.mainchain_torsion(1), requires_grad=True)
    psi = torch.tensor(res.mainchain_torsion(2), requires_grad=True)
    prob = self._interpolate(phi, psi)
    gradients = grad([prob], [phi, psi])
    return float(gradients[torsion_id.torsion() - 1])

  def eval_dof_derivative(self, dof_id, torsion_id, pose, sfxn, weights):
    res = pose.residue(torsion_id.rsd())
    if not torsion_id.valid() or torsion_id.type() != rosetta.core.id.TorsionType.BB:
      return 0.0

    phi = torch.tensor(res.mainchain_torsion(1), requires_grad=True)
    psi = torch.tensor(res.mainchain_torsion(2), requires_grad=True)
    prob = self._interpolate(phi, psi)
    gradients = grad([prob], [phi, psi])
    return float(gradients[torsion_id.torsion() - 1])

def get_betafold_scoring_function(distograms, torsions,
                                  distance_args=None,
                                  torsion_args=None,
                                  base_score="score2_smooth",
                                  distance_weight=-1.0,
                                  torsion_weight=-1.0):
  if distance_args is None:
    distance_args = {}
  if torsion_args is None:
    torsion_args = {}

  distance = DistanceTerm(*distograms, **distance_args)
  torsion = TorsionTerm(*torsions, **torsion_args)

  score = create_score_function(base_score)
  score.add_extra_method(torsion.scoreType, torsion_weight, torsion)
  score.add_extra_method(torsion.scoreType, distance_weight, distance)

  return score


import requests
from lxml import etree
from fake_useragent import UserAgent

urls_list = []
url = 'https://www.21food.cn/company/companylist_catid-03.html'
print(UserAgent().random)
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}

response = requests.get(url=url, headers=headers)
print(response.status_code)
html = etree.HTML(response.text)

li_list = html.xpath('//div[@class="ec_tit_nv ec_tit_nvg"]/ul/li')

for li in li_list:
    href = 'https://www.21food.cn' + li.xpath('./a/@href')[0]  # /company/companylist_catid-03007.html
    # print(href)
    urls_list.append(href)

for pa in range(3, 6):
    company_list = []
    # 选择一个分类进行网站反爬测试
    company_url = urls_list[pa]
    c_response = requests.get(url=company_url, headers=headers)
    print(c_response.status_code)
    c_html = etree.HTML(c_response.text)
    dd_list = c_html.xpath('//div[@class="qy_list_main auto"]/div[1]/dl/dd')
    # dd_list = c_html.xpath('/html/body/div[4]')
    for dd in dd_list:

        c_href = dd.xpath('.//span[@class="qylis_tt"]/a/@href')[0]
        c_name = dd.xpath('.//span[@class="qylis_tt"]/a/text()')[0]
        c_produce = dd.xpath('.//div[@class="qy_lis_l_jmo_ll"]/ul/li[2]/span/text()')[0].strip(' \n')
        company_list.append(c_href)
    for c_href in company_list:
        print('获取网页信息', c_href)
        detail_response = requests.get(url=c_href, headers=headers)

        data = detail_response.text
        print(detail_response.status_code)

        # print(c_name, c_produce)


#usage: python rap2cog.py infile(.m8 from rapsearch) outfile

from sys import argv

rap=open(argv[1]) #rapsearch result
specie=open("species") #specie annotation
function=open("fun.txt") #function category
totalinf=open("kog")# or whog  contains information on each COG, including the COG name,functional classification (using a one-letter code), function description, and the the list of proteins (or domains) from all  66 complete genomes included in the COG database.
equal=open("pa")#database file
out=open(argv[2],"w")#output file

dicrap={}
org={}
func={}
total={}
diceq={}
#
for i in rap:
	q=i.split("\t")
	if i.startswith("#")==False:
		if q[0] not in dicrap:
			dicrap[q[0]]=q[1] #dicionario with query and hits

for u in specie:
	p=u.split("  ")
	org[p[1].strip()]=(p[-1].strip()).strip("\n")
print (org)

#
for e in function:
	if e.startswith(" ["):
		v=e.split("]")
		func[v[0].strip()+"]"]=cat+v[1].strip("\n") #dicionary: [J] - INFORMATION  - Translation
	else:
		cat=(e.strip("\n"))+"\t"
#
for a in totalinf:
	if a.startswith("["):
		cat2=a.split(" ",2)
	elif a.startswith(" "):
		li=[]
		z=a.split(":")
		if len(z)!=1:
			line=z[0].strip()
		li.append(cat2[0])
		li.append((cat2[-1].strip()).strip("\n"))
		li.append(line)
		acess=((z[-1].strip()).strip("\n")).split()
		for r in acess:
			total[r]=li #dictionary: hit= [[H],glutamate,Afu]
#
for o in equal:
	if o.startswith("  ")==False:
		la=o.split(" ")
		num=la[4].strip(")")
		if float(num)<= 0.00001:
			if la[0] not in diceq and la[0]!=la[2]:
				ttt=[]
				ttt.append(la[2])
				diceq[la[0]]=ttt
			elif la[0]!=la[2]:
				diceq[la[0]].append(la[2])

out.write("Gene\tHit\tCategory\tSubcategory\tDescription\tOrganism\n")

for key, value in dicrap.items():
	if value in total:
		out.write(key+"\t"+value+"\t")
		if total[value][0] in func:
			out.write(func[total[value][0]]+"\t")
		else:
			out.write(total[value][0]+"\t"+"na"+"\t")
		out.write(total[value][1]+"\t")
		out.write(org[total[value][2]]+"\n")
	elif value in diceq:
		for t in diceq[value]:
			if t in total:
				out.write(key+"\t"+value+"\t")
				if total[t][0] in func:
					out.write(func[total[t][0]]+"\t")
				else:
					out.write(total[t][0]+"\t"+"na"+"\t")
				out.write(total[t][1]+"\t")
				out.write(org[total[t][2]]+"\n")
				break

rap.close()
specie.close()
function.close()
totalinf.close()
out.close()
equal.close()


from sklearn import datasets
from sklearn.linear_model import LogisticRegression
import numpy as np

def load_data():
    return datasets.load_iris(return_X_y=True)

def binary_classification(X, binary_label):
    # input : X (features), shape:(number of samples, number of features)
    # input : binary_label (1 or 0), shape:(number of samples, )
    # output : probability to belong to that class, shape:(number of samples, )
    binary_model = LogisticRegression(solver='lbfgs')  # Do not change the solver.
    # print(binary_label)
    binary_model.fit(X, binary_label)
    # print(binary_label)
    predicted_p = binary_model.predict_proba(X)
    # print(predicted_p)
    class1 = []
    for i in range(len(predicted_p)):
        # print(predicted_p[i][1])
        class1.append(predicted_p[i][1])
    # print(predicted_p)
    # predicted_p = sum(class1) / len(class1)
    predicted_p = class1
    predicted_p = np.array(predicted_p)
    predicted_p.transpose()
    print(np.array(predicted_p))
    #print(predicted_p.transpose())

    return np.array(predicted_p.transpose()) # here
    # return np.array(class1)

def multiclass_classification(X, y):
    # input : X (features), shape:(number of samples, number of features)
    # input : y (labels), shape:(number of samples,)
    # output : multiclass classification accuracy, shape:(1, )
    res = -1
    label = -1
    # for i in range(len(y)):
    #    p_tmp = binary_classification(X,i)
    #    if p_tmp>res:
    #        res = p_tmp
    #        label = i
    arg = []
    arg1 = binary_classification(X, y == 0)
    #arg.append(sum(arg1) / len(arg1))
    arg2 = binary_classification(X, y == 1)
    #arg.append(sum(arg2) / len(arg2))
    arg3 = binary_classification(X, y == 2)
    #arg.append(sum(arg3) / len(arg3))
    lab = -1
    for i in range(len(y)):
        acc = max(arg1[i],arg2[i],arg3[i])
        if acc == arg1[i]:
            lab = 0
        elif acc == arg2[i]:
            lab = 1
        elif acc == arg3[i]:
            lab = 2
        arg.append(lab)

    cnt = 0
    for i in range(len(y)):
        # print(y[i])
        if arg[i] == y[i]:
            cnt += 1
    # print(len(X[1]))
    # print(cnt)
    accuracy = cnt / len(y)

    return accuracy

def main():
    data = load_data()
    #acc = binary_classification(data[0], data[1] == 1)
    #print( sum(acc) / len(acc))
    #print(data[1])
    accuracy = multiclass_classification(data[0], data[1])
    print('Accuracy of multiclass classification is %f.' % (accuracy))

if __name__ == '__main__':
    main()


# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.

from full_route_utils import *

@route("/vendors/<vid>/contacts/edit-contact-<cid>")
@post("/vendors/<vid>/contacts/edit-contact-<cid>")
@view("views/vendors/edit_contact", inv = inv)
def edit_vendor_contact(vid, cid):
    check_user()
    contact_info = select_vendor_contact_info(cid)
    if request.POST.get("edit-contact"):
        contact_name = request.POST.get("name")
        contact_title = request.POST.get("title")
        phone = request.POST.get("phone")
        alt_phone = request.POST.get("alt-phone")
        email = request.POST.get("email")
        update_vendor_contact(cid, contact_name, contact_title, phone,
                              alt_phone, email)
        redirect("/vendors/{0}/contacts/edit-contact-{1}".format(vid, cid))
    else:
        return dict(contact_info = contact_info, vid = vid)

@route("/vendors/<vid>/products/add-product")
@post("/vendors/<vid>/products/add-product")
@view("views/vendors/add_product", inv = inv)
def add_vendor_product(vid):
    check_user()
    item_list = select_upc_list()
    if request.POST.get("add-product"):
        upc = request.POST.get("upc")
        insert_product_vendor(vid, upc)
        return dict(upc = upc, item_list = item_list, vid = vid)
    else:
        return dict(upc = None, item_list = item_list, vid = vid)

@route("/vendors/<vid>/contacts/add-contact")
@post("/vendors/<vid>/contacts/add-contact")
@view("views/vendors/add_contact", inv = inv)
def add_vendor_contact(vid):
    check_user()
    if request.POST.get("add-contact"):
        contact_name = request.POST.get("name")
        contact_title = request.POST.get("title")
        phone = request.POST.get("phone")
        alt_phone = request.POST.get("alt-phone")
        email = request.POST.get("email")
        insert_vendor_contact(vid, contact_name, contact_title, phone,
                       alt_phone, email)
        return dict(contact_name = contact_name, vid = vid)
    else:
        return dict(contact_name = None, vid = vid)

@route("/vendors/<vid>/contacts")
@view("views/vendors/vendor_contacts", inv = inv)
def vendor_contacts(vid):
    check_user()
    v_info = get_vendor_info(vid)
    v_contacts = select_vendor_contacts(vid)
    return dict(contacts = v_contacts,
                    vendor_info = v_info)

@route("/vendors/<vid>/products")
@view("views/vendors/vendor_products", inv = inv)
def vendor_contacts(vid):
    check_user()
    v_info = get_vendor_info(vid)
    v_products = select_vendor_products(vid)
    return dict(vendor_products = v_products,
                    vendor_info = v_info)

@route("/vendors/<vid>")
@view("views/vendors/vendor_info", inv = inv)
def vendor_info(vid):
    check_user()
    v_info = get_vendor_info(vid)
    v_contacts = select_vendor_contacts(vid)
    v_products = select_vendor_products(vid)
    return dict(vendor_info = v_info, contacts = v_contacts,
                    vendor_products = v_products)

@route("/vendors/<vid>/edit-vendor")
@post("/vendors/<vid>/edit-vendor")
@view("views/vendors/edit_vendor", inv = inv)
def edit_vendor(vid):
    check_user()
    vendor_info = get_vendor_info(vid)
    if request.POST.get("update-vendor"):
        old_vendor_id = vid
        new_vendor_id = request.POST.get("vendor-id")
        vendor_name = request.POST.get("vendor-name")
        phone = request.POST.get("phone")
        fax = request.POST.get("fax")
        website = request.POST.get("website")
        email = request.POST.get("email")
        street = request.POST.get("street")
        city = request.POST.get("city")
        state = request.POST.get("state")
        zip = request.POST.get("zip")
        country = request.POST.get("country")
        update_vendor_info(old_vendor_id, new_vendor_id, vendor_name,
                       phone, fax, website, email, street, city, state,
                       zip, country)
        redirect("/vendors/{0}/edit-vendor".format(new_vendor_id))
    else:
        return dict(vendor_info = vendor_info)

@route("/vendors/add-vendor")
@post("/vendors/add-vendor")
@view("views/vendors/add_vendor", inv = inv)
def add_vendor():
    check_user()
    vendors = select_vendors()
    if request.POST.get("add-vendor"):
        vendor_id = request.POST.get("vendor-id")
        vendor_name = request.POST.get("vendor-name")
        phone = request.POST.get("phone")
        fax = request.POST.get("fax")
        website = request.POST.get("website")
        email = request.POST.get("email")
        street = request.POST.get("street")
        city = request.POST.get("city")
        state = request.POST.get("state")
        zip = request.POST.get("zip")
        country = request.POST.get("country")
        insert_new_vendor(vendor_id, vendor_name, phone, fax, website,
                          email, street, city, state, zip, country)
        return dict(new_vendor = vendor_name)
    else:
        return dict(new_vendor = None)

@route("/vendors")
@view("views/vendors/main", inv = inv)
def vendors():
    check_user()
    vendors = select_vendors()
    return dict(vendors = vendors)


import json
import logging

from autogpt.config import AIDirectives, AIProfile, Config
from autogpt.core.configuration import SystemConfiguration, UserConfigurable
from autogpt.core.prompting import (
    ChatPrompt,
    LanguageModelClassification,
    PromptStrategy,
)
from autogpt.core.prompting.utils import json_loads
from autogpt.core.resource.model_providers.schema import (
    AssistantChatMessageDict,
    ChatMessage,
    ChatModelProvider,
    CompletionModelFunction,
)
from autogpt.core.utils.json_schema import JSONSchema

logger = logging.getLogger(__name__)

class AgentProfileGeneratorConfiguration(SystemConfiguration):
    model_classification: LanguageModelClassification = UserConfigurable(
        default=LanguageModelClassification.SMART_MODEL
    )
    _example_call: object = [
        {
            "type": "function",
            "function": {
                "name": "create_agent",
                "arguments": {
                    "name": "CMOGPT",
                    "description": (
                        "a professional digital marketer AI that assists Solopreneurs "
                        "in growing their businesses by providing "
                        "world-class expertise in solving marketing problems "
                        "for SaaS, content products, agencies, and more."
                    ),
                    "directives": {
                        "best_practices": [
                            (
                                "Engage in effective problem-solving, prioritization, "
                                "planning, and supporting execution to address your "
                                "marketing needs as your virtual "
                                "Chief Marketing Officer."
                            ),
                            (
                                "Provide specific, actionable, and concise advice to "
                                "help you make informed decisions without the use of "
                                "platitudes or overly wordy explanations."
                            ),
                            (
                                "Identify and prioritize quick wins and cost-effective "
                                "campaigns that maximize results with minimal time and "
                                "budget investment."
                            ),
                            (
                                "Proactively take the lead in guiding you and offering "
                                "suggestions when faced with unclear information or "
                                "uncertainty to ensure your marketing strategy remains "
                                "on track."
                            ),
                        ],
                        "constraints": [
                            "Do not suggest illegal or unethical plans or strategies.",
                            "Take reasonable budgetary limits into account.",
                        ],
                    },
                },
            },
        }
    ]
    system_prompt: str = UserConfigurable(
        default=(
            "Your job is to respond to a user-defined task, given in triple quotes, by "
            "invoking the `create_agent` function to generate an autonomous agent to "
            "complete the task. "
            "You should supply a role-based name for the agent (_GPT), "
            "an informative description for what the agent does, and 1 to 5 directives "
            "in each of the categories Best Practices and Constraints, "
            "that are optimally aligned with the successful completion "
            "of its assigned task.\n"
            "\n"
            "Example Input:\n"
            '"""Help me with marketing my business"""\n\n'
            "Example Call:\n"
            "```\n"
            f"{json.dumps(_example_call, indent=4)}"
            "\n```"
        )
    )
    user_prompt_template: str = UserConfigurable(default='"""{user_objective}"""')
    create_agent_function: dict = UserConfigurable(
        default=CompletionModelFunction(
            name="create_agent",
            description="Create a new autonomous AI agent to complete a given task.",
            parameters={
                "name": JSONSchema(
                    type=JSONSchema.Type.STRING,
                    description="A short role-based name for an autonomous agent.",
                    required=True,
                ),
                "description": JSONSchema(
                    type=JSONSchema.Type.STRING,
                    description=(
                        "An informative one sentence description "
                        "of what the AI agent does"
                    ),
                    required=True,
                ),
                "directives": JSONSchema(
                    type=JSONSchema.Type.OBJECT,
                    properties={
                        "best_practices": JSONSchema(
                            type=JSONSchema.Type.ARRAY,
                            minItems=1,
                            maxItems=5,
                            items=JSONSchema(
                                type=JSONSchema.Type.STRING,
                            ),
                            description=(
                                "One to five highly effective best practices "
                                "that are optimally aligned with the completion "
                                "of the given task"
                            ),
                            required=True,
                        ),
                        "constraints": JSONSchema(
                            type=JSONSchema.Type.ARRAY,
                            minItems=1,
                            maxItems=5,
                            items=JSONSchema(
                                type=JSONSchema.Type.STRING,
                            ),
                            description=(
                                "One to five reasonable and efficacious constraints "
                                "that are optimally aligned with the completion "
                                "of the given task"
                            ),
                            required=True,
                        ),
                    },
                    required=True,
                ),
            },
        ).schema
    )

class AgentProfileGenerator(PromptStrategy):
    default_configuration: AgentProfileGeneratorConfiguration = (
        AgentProfileGeneratorConfiguration()
    )

    def __init__(
        self,
        model_classification: LanguageModelClassification,
        system_prompt: str,
        user_prompt_template: str,
        create_agent_function: dict,
    ):
        self._model_classification = model_classification
        self._system_prompt_message = system_prompt
        self._user_prompt_template = user_prompt_template
        self._create_agent_function = CompletionModelFunction.parse(
            create_agent_function
        )

    @property
    def model_classification(self) -> LanguageModelClassification:
        return self._model_classification

    def build_prompt(self, user_objective: str = "", **kwargs) -> ChatPrompt:
        system_message = ChatMessage.system(self._system_prompt_message)
        user_message = ChatMessage.user(
            self._user_prompt_template.format(
                user_objective=user_objective,
            )
        )
        prompt = ChatPrompt(
            messages=[system_message, user_message],
            functions=[self._create_agent_function],
        )
        return prompt

    def parse_response_content(
        self,
        response_content: AssistantChatMessageDict,
    ) -> tuple[AIProfile, AIDirectives]:
        """Parse the actual text response from the objective model.

        Args:
            response_content: The raw response content from the objective model.

        Returns:
            The parsed response.

        """
        try:
            arguments = json_loads(
                response_content["tool_calls"][0]["function"]["arguments"]
            )
            ai_profile = AIProfile(
                ai_name=arguments.get("name"),
                ai_role=arguments.get("description"),
            )
            ai_directives = AIDirectives(
                best_practices=arguments["directives"].get("best_practices"),
                constraints=arguments["directives"].get("constraints"),
                resources=[],
            )
        except KeyError:
            logger.debug(f"Failed to parse this response content: {response_content}")
            raise
        return ai_profile, ai_directives

async def generate_agent_profile_for_task(
    task: str,
    app_config: Config,
    llm_provider: ChatModelProvider,
) -> tuple[AIProfile, AIDirectives]:
    """Generates an AIConfig object from the given string.

    Returns:
    AIConfig: The AIConfig object tailored to the user's input
    """
    agent_profile_generator = AgentProfileGenerator(
        **AgentProfileGenerator.default_configuration.dict()  # HACK
    )

    prompt = agent_profile_generator.build_prompt(task)

    # Call LLM with the string as user input
    output = (
        await llm_provider.create_chat_completion(
            prompt.messages,
            model_name=app_config.smart_llm,
            functions=prompt.functions,
        )
    ).response

    # Debug LLM Output
    logger.debug(f"AI Config Generator Raw Output: {output}")

    # Parse the output
    ai_profile, ai_directives = agent_profile_generator.parse_response_content(output)

    return ai_profile, ai_directives


import logging

try:
    from swiglpk import *
except ImportError:
    from glpk import *

class SolverSC1:
    def __init__(self, dataflow, verbose, lp_filename):
        self.dataflow = dataflow
        self.verbose = verbose
        self.lp_filename = lp_filename

        self.colV = {}  # dict use for storing gamma's variable column
        self.col_m0 = {}  # dict use for storing bds's variable column
        self.col_fm0 = {}  # dict use for storing FM0's variable column

    def compute_initial_marking(self):
        self.__init_prob()  # Modify parameters
        self.__create_col()  # Add Col on prob
        self.__create_row()  # Add Row (constraint) on prob
        self.__solve_prob()  # Launch the solver and set preload of the graph
        glp_delete_prob(self.prob)
        glp_free_env()
        del self.prob  # Del prob
        return self.Z  # Return the total amount find by the solver

    def __init_prob(self):  # Modify parameters
        logging.info("Generating initial marking problem")

        self.prob = glp_create_prob()
        glp_set_prob_name(self.prob, "min_preload")
        glp_set_obj_dir(self.prob, GLP_MIN)

        # GLPK parameters:
        self.glpk_param = glp_smcp()
        glp_init_smcp(self.glpk_param)  # Do it before modify parameters
        self.glpk_param.presolve = GLP_ON
        self.glpk_param.msg_lev = GLP_MSG_ALL
        if not self.verbose:
            self.glpk_param.msg_lev = GLP_MSG_ERR
        self.glpk_param.meth = GLP_DUALP
        self.glpk_param.out_frq = 2000  # consol print frequency

    def __create_col(self):  # Add Col on prob
        # Counting column
        tot_phase_count = 0
        if self.dataflow.is_csdf:
            for task in self.dataflow.get_task_list():
                tot_phase_count += self.dataflow.get_phase_count(task)
                if self.dataflow.is_pcg:
                    tot_phase_count += self.dataflow.get_ini_phase_count(task)
        else:
            tot_phase_count = self.dataflow.get_task_count()

        col_count = tot_phase_count + self.dataflow.get_arc_count() * 2
        logging.info("Number of column: " + str(col_count))

        # Create column
        glp_add_cols(self.prob, col_count)

        col = 1
        # Create column bds (M0)
        for arc in self.dataflow.get_arc_list():
            self.__add_col_m0(col, "M0" + str(arc), arc)
            col += 1

        # Create column bds (FM0)
        for arc in self.dataflow.get_arc_list():
            self.__add_col_fm0(col, "FM0" + str(arc), arc)
            col += 1

        # Create column lambda (v)
        for task in self.dataflow.get_task_list():
            phase_count = 1
            if self.dataflow.is_csdf:
                phase_count = self.dataflow.get_phase_count(task)
            if self.dataflow.is_pcg:
                phase_count += self.dataflow.get_ini_phase_count(task)
            for i in xrange(phase_count):
                self.__add_col_v(col, str(task) + "/" + str(i))
                col += 1

    def __create_row(self):  # Add Row (constraint) on prob
        # Counting row
        f_row_count = self.dataflow.get_arc_count()
        for arc in self.dataflow.get_arc_list():
            if self.dataflow.is_arc_reentrant(arc):
                f_row_count -= 1

        row_count = 0
        for arc in self.dataflow.get_arc_list():
            source = self.dataflow.get_source(arc)
            target = self.dataflow.get_target(arc)
            if not self.dataflow.is_arc_reentrant(arc):
                if self.dataflow.is_sdf:
                    row_count += 1
                if self.dataflow.is_csdf and not self.dataflow.is_pcg:
                    row_count += self.dataflow.get_phase_count(source) * self.dataflow.get_phase_count(target)
                if self.dataflow.is_pcg:
                    source_phase_count = self.dataflow.get_phase_count(source) + self.dataflow.get_ini_phase_count(
                        source)
                    target_phase_count = self.dataflow.get_phase_count(target) + self.dataflow.get_ini_phase_count(
                        target)
                    row_count += source_phase_count * target_phase_count

        # Create row
        logging.info("Number of rows: " + str(row_count + f_row_count))
        glp_add_rows(self.prob, row_count + f_row_count)

        self.varArraySize = row_count * 3 + f_row_count * 2 + 1
        logging.info("Var array size: " + str(self.varArraySize))
        self.var_row = intArray(self.varArraySize)
        self.var_col = intArray(self.varArraySize)
        self.var_coef = doubleArray(self.varArraySize)

        # BEGUIN FILL ROW
        self.k = 1
        row = 1
        ########################################################################
        #                       Constraint FM0*step - M0 = 0                   #
        ########################################################################
        for arc in self.dataflow.get_arc_list():
            if not self.dataflow.is_arc_reentrant(arc):
                arc_gcd = self.dataflow.get_gcd(arc)
                self.__add_f_row(row, arc, arc_gcd)
                row += 1

        ########################################################################
        #                       Constraint u-u'+M0 >= W1+1                     #
        ########################################################################
        for arc in self.dataflow.get_arc_list():
            source = self.dataflow.get_source(arc)
            target = self.dataflow.get_target(arc)
            if not self.dataflow.is_arc_reentrant(arc):
                range_source = self.__get_range_phases(source)
                range_target = self.__get_range_phases(target)
                prod_list = self.__get_prod_rate_list(arc)
                cons_list = self.__get_cons_rate_list(arc)
                if self.dataflow.is_pcg:
                    threshold_list = self.__get_threshold_list(arc)
                arc_gcd = self.dataflow.get_gcd(arc)

                pred_prod = 0
                for source_phase in xrange(range_source):  # source/prod/out normaux
                    if source_phase > 0:
                        pred_prod += prod_list[source_phase - 1]

                    pred_cons = 0
                    cons = 0
                    for target_phase in xrange(range_target):  # target/cons/in normaux
                        cons += cons_list[target_phase]
                        if target_phase > 0:
                            pred_cons += cons_list[target_phase - 1]

                        w = cons - pred_prod - arc_gcd
                        if self.dataflow.is_pcg:
                            w += pred_cons + threshold_list[target_phase] - cons

                        str_v1 = str(source) + "/" + str(source_phase)
                        str_v2 = str(target) + "/" + str(target_phase)
                        self.__add_row(row, str_v1, str_v2, arc, w)
                        row += 1
                        # END FILL ROW

    def __solve_prob(self):  # Launch the solver and set preload of the graph
        logging.info("loading matrix ...")
        glp_load_matrix(self.prob, self.varArraySize - 1, self.var_row, self.var_col, self.var_coef)

        if self.lp_filename is not None:
            problem_location = str(glp_write_lp(self.prob, None, self.lp_filename))
            logging.info("Writing problem: " + str(problem_location))

        logging.info("solving problem ...")
        ret = str(glp_simplex(self.prob, self.glpk_param))
        logging.info("Solver return: " + ret)

        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            for arc in self.dataflow.get_arc_list():
                logging.debug(str(arc) + " M0: " + str(glp_get_col_prim(self.prob, self.col_m0[arc])) +
                              " FM0: " + str(glp_get_col_prim(self.prob, self.col_fm0[arc])))
            for arc in self.dataflow.get_arc_list():
                source = self.dataflow.get_source(arc)
                target = self.dataflow.get_target(arc)
                for phaseS in xrange(self.__get_range_phases(source)):
                    for phaseT in xrange(self.__get_range_phases(target)):
                        logging.debug(
                            str(arc) + " V" + str(source) + "/" + str(phaseS) + ": " +
                            str(glp_get_col_prim(self.prob, self.colV[str(source) + "/" + str(phaseS)]))
                            + " V" + str(target) + "/" + str(phaseT) + ": " +
                            str(glp_get_col_prim(self.prob, self.colV[str(target) + "/" + str(phaseT)])))

        self.Z = glp_get_obj_val(self.prob)

        opt_buffer = True
        buf_rev_tot = 0

        # Revision of the final bds (in case of non integer variable)
        for arc in self.dataflow.get_arc_list():
            if not self.dataflow.is_arc_reentrant(arc):
                buf = glp_get_col_prim(self.prob, self.col_m0[arc])
                fm0 = glp_get_col_prim(self.prob, self.col_fm0[arc])
                gcd = self.dataflow.get_gcd(arc)
                # print arc, "buf", buf, "fm0", fm0
                if fm0 % 1 == 0:
                    self.dataflow.set_initial_marking(arc, int(buf))
                    buf_rev_tot += int(buf)
                else:
                    opt_buffer = False
                    self.dataflow.set_initial_marking(arc, int(fm0 + 1) * gcd)
                    buf_rev_tot += int(fm0 + 1) * gcd

        logging.info("SC1 Mem tot (no reentrant): " + str(self.Z) + " REV: " + str(buf_rev_tot))
        if opt_buffer:
            logging.info("Solution SC1 Optimal !!")
        else:
            logging.info("Solution SC1 Not Optimal:-(")

    # Add a variable lamda
    def __add_col_v(self, col, name):
        glp_set_col_name(self.prob, col, name)
        glp_set_col_bnds(self.prob, col, GLP_LO, 0, 0)
        glp_set_obj_coef(self.prob, col, 0.0)
        self.colV[name] = col

    # Add a variable M0
    def __add_col_m0(self, col, name, arc):
        glp_set_col_name(self.prob, col, name)
        glp_set_col_bnds(self.prob, col, GLP_LO, 0, 0)
        glp_set_obj_coef(self.prob, col, 1.0)
        self.col_m0[arc] = col

    # Add a variable FM0
    def __add_col_fm0(self, col, name, arc):
        glp_set_col_kind(self.prob, col, GLP_IV)
        glp_set_col_name(self.prob, col, name)
        glp_set_col_bnds(self.prob, col, GLP_LO, 0, 0)
        glp_set_obj_coef(self.prob, col, 0.0)
        self.col_fm0[arc] = col

    # Add a constraint: lambda1 - lambda2 + M0 > W1
    def __add_row(self, row, str_v1, str_v2, arc, w):
        self.var_row[self.k] = row
        self.var_col[self.k] = self.colV[str_v1]
        self.var_coef[self.k] = 1.0
        self.k += 1

        self.var_row[self.k] = row
        self.var_col[self.k] = self.colV[str_v2]
        self.var_coef[self.k] = -1.0
        self.k += 1

        self.var_row[self.k] = row
        self.var_col[self.k] = self.col_m0[arc]
        self.var_coef[self.k] = 1.0
        self.k += 1

        glp_set_row_bnds(self.prob, row, GLP_LO, w + 0.001, 0.0)  # W1+1 cause there is no strict bound with GLPK
        glp_set_row_name(self.prob, row, "r_" + str(row))

    # Add a constraint: FM0*step = M0
    def __add_f_row(self, row, arc, step):
        self.var_row[self.k] = row
        self.var_col[self.k] = self.col_fm0[arc]
        self.var_coef[self.k] = float(step)
        self.k += 1

        self.var_row[self.k] = row
        self.var_col[self.k] = self.col_m0[arc]
        self.var_coef[self.k] = -1.0
        self.k += 1

        glp_set_row_bnds(self.prob, row, GLP_FX, 0.0, 0.0)
        glp_set_row_name(self.prob, row, "step" + str(arc))

    def __get_range_phases(self, task):
        if self.dataflow.is_sdf:
            return 1
        range_task = self.dataflow.get_phase_count(task)
        if self.dataflow.is_pcg:
            range_task += self.dataflow.get_ini_phase_count(task)
        return range_task

    def __get_prod_rate_list(self, arc):
        if self.dataflow.is_sdf:
            return [self.dataflow.get_prod_rate(arc)]
        prod_list = self.dataflow.get_prod_rate_list(arc)
        if self.dataflow.is_pcg:
            prod_list = self.dataflow.get_ini_prod_rate_list(arc) + prod_list
        return prod_list

    def __get_cons_rate_list(self, arc):
        if self.dataflow.is_sdf:
            return [self.dataflow.get_cons_rate(arc)]
        cons_list = self.dataflow.get_cons_rate_list(arc)
        if self.dataflow.is_pcg:
            cons_list = self.dataflow.get_ini_cons_rate_list(arc) + cons_list
        return cons_list

    def __get_threshold_list(self, arc):
        return self.dataflow.get_ini_threshold_list(arc) + self.dataflow.get_threshold_list(arc)


# coding: utf-8
import os
import uuid
from datetime import datetime

from bmp import app
from bmp.apis.base import BaseApi
from bmp.models.upload import Upload
from flask import request
from flask import send_file

class UploadApi(BaseApi):
    route = ["/upload"]

    def __save_file(self, file):
        path = "%s/%s" % (app.config["UPLOAD_FOLDER"], datetime.now().strftime("%Y-%m-%d"))
        path = path.replace("/", os.sep)
        if not os.path.exists(app.root_path + path):
            os.makedirs(app.root_path + path)

        uid = "%s" % uuid.uuid1()

        Upload.add(file.filename, uid)

        file_path = os.path.join(path, uid)
        file.save(app.root_path + file_path)
        return file_path

    def get(self):
        submit = request.args["path"]
        uuid = submit.split(os.sep)[-1]
        name = Upload.get_name(uuid)
        if not name:
            return send_file(app.root_path + submit, as_attachment=True)
        return send_file(app.root_path + submit, as_attachment=True, attachment_filename=name)

    def post(self):
        _dict = {}
        for name in request.files:
            _dict[name] = self.__save_file(request.files[name])
        return self.succ(_dict)

if __name__ == "__main__":
    print(app.root_path)


nom_t = str(input("ingrese el nombre del trabajador: "))
codigo = str(input("ingrese el codigo de trabajador: "))
productos = int(input("ingrese cuantos productos vendio en el mes: "))
bonificacion = 0
if productos >= 35:
    bonificacion = 200000

if productos < 35:
    bonificacion = 100000

if productos < 10:
    bonificacion = 50000

print(nom_t, "su bonificacion por vender ",
      productos, "productos es de ", bonificacion)


# 给定一个数组 prices ，它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
#
# 你只能选择 某一天 买入这只股票，并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
#
# 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润，返回 0 。
#
#
#
# 示例 1：
#
# 输入：[7,1,5,3,6,4]
# 输出：5
# 解释：在第 2 天（股票价格 = 1）的时候买入，在第 5 天（股票价格 = 6）的时候卖出，最大利润 = 6-1 = 5 。
#      注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格；同时，你不能在买入前卖出股票。
# 示例 2：
#
# 输入：prices = [7,6,4,3,1]
# 输出：0
# 解释：在这种情况下, 没有交易完成, 所以最大利润为 0。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # 单调减栈
        # 记录弹出的最低价格
        # 记录最大差值
        # stack = []
        # ans = 0
        # min_price = float("inf")
        # for price in prices:
        #     while stack and stack[-1] < price:
        #         min_price = min(min_price, stack.pop())
        #         ans = max(ans, price - min_price)
        #     stack.append(price)
        # return ans

        # 动态规划
        # dp[i]代表第i个price的与之前最小值
        # dp = [float("inf")] * len(prices)
        # ans = 0
        # for i in range(1, len(prices)):
        #     dp[i] = min(prices[i-1], dp[i-1])
        #     ans = max(prices[i]- dp[i], ans)
        # return ans
        #
        # 状态 0 cash in hand after selling 卖了股票后钱在手
        # 状态 1 stock in hand 股票在手
        dp = [[0,0] for _ in range(len(prices))]
        # 第一天买了股票，利润为-price[0]
        # 第一天不可能卖，所以为0
        dp[0][1] = -prices[0]
        for i in range(1, len(prices)):
            # 这一天手上的钱可能是前一天手上的钱或者前一天手上的股票今天卖了的钱
            dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
            # 这一天手上的股票可能是前一天手上的股票或者今天刚买的股票
            dp[i][1] = max(dp[i-1][1],-prices[i])
        return dp[-1][0]

动态规划/121.买卖股票的最佳时机.py

121.买卖股票的最佳时机.py