Exemplo n.º 1
0
    def logIn(self, username, pwd):
        """
        Logs in a user
        :param username: username
        :param pwd: password
        :return: None @TODO: Maybe return True/False?
                            (Exceptions implemented, don't think it's worth doing)
        @TODO: Detailed comments
        """
        conn = create_connection("Acc.db")
        cur = conn.cursor()
        try:
            cur.execute("SELECT * FROM Accounts WHERE Accounts.username=?", (username,))
        except sqlite3.OperationalError:
            raise Exception("User doesn't exist")
        rows = cur.fetchall()
        for row in rows:
            salt = row[4]
            stPwd = row[5]
            pwdhash = hashlib.pbkdf2_hmac('sha512', pwd.encode('utf-8'), salt.encode('ascii'), 100000)
            pwdhash = binascii.hexlify(pwdhash).decode('ascii')
            print()
            if pwdhash != stPwd:
                raise Exception("Invalid password")

            self.name = row[1]
            self.surname = row[2]
            self.username = row[3]
            self.email = row[6]
            self.height = row[7]
            self.weight = Weight(row[8], row[9])
            self.uID = row[10]

        self.DBInfo = DBInfo(self.uID)
Exemplo n.º 2
0
class Linear(Module):
    """
    Linear Layer (feed-forward layer)
    """
    def __init__(self, in_dim, out_dim):
        super(Linear, self).__init__()
        self.in_dim = in_dim
        self.out_dim = out_dim
        self.weight = Weight((in_dim, out_dim))
        self.bias = Weight((1, out_dim))

    def fprop(self, input_data):
        # high_dimension_input = input_data.ndim > 2
        #
        # # Reshape input
        # if high_dimension_input:
        #     input_data = input_data.reshape(input_data.shape[0], -1)

        self.output = np.dot(input_data, self.weight.D) + self.bias.D

        # # Reshape output
        # if high_dimension_input:
        #     self.output = self.output.reshape(self.output.shape[0], -1)

        return self.output

    # TODO: Rename input_data -> prev_layer_output
    def bprop(self, input_data, grad_output):
        # orig_input_data_shape = input_data.shape
        # high_dimension_input = input_data.ndim > 2
        #
        # # Reshape input and grad_output
        # if high_dimension_input:
        #     input_data  = input_data.reshape(input_data.shape[0], -1)
        #     grad_output = grad_output.reshape(grad_output.shape[0], -1)

        # self.weight.grad = self.weight.grad + np.dot(input_data.T, grad_output)
        # self.bias.grad   = self.bias.grad + grad_output.sum(axis=0)
        self.weight.grad = np.dot(input_data.T, grad_output)
        self.bias.grad = grad_output.sum(axis=0)
        self.grad_input = np.dot(grad_output, self.weight.D.T)

        # if high_dimension_input:
        #     self.grad_input = self.grad_input.reshape(orig_input_data_shape)

        return self.grad_input

    def update(self, params):
        self.weight.update(params)
        self.bias.update(params)

    def share(self, m):
        self.weight = m.weight
        self.bias = m.bias
Exemplo n.º 3
0
class Linear(Module):
    """
    Linear Layer (feed-forward layer)
    """
    def __init__(self, in_dim, out_dim):
        super(Linear, self).__init__()
        self.in_dim  = in_dim
        self.out_dim = out_dim
        self.weight  = Weight((in_dim, out_dim))
        self.bias    = Weight((1, out_dim))

    def fprop(self, input_data):
        # high_dimension_input = input_data.ndim > 2
        #
        # # Reshape input
        # if high_dimension_input:
        #     input_data = input_data.reshape(input_data.shape[0], -1)

        self.output = np.dot(input_data, self.weight.D) + self.bias.D

        # # Reshape output
        # if high_dimension_input:
        #     self.output = self.output.reshape(self.output.shape[0], -1)

        return self.output

    # TODO: Rename input_data -> prev_layer_output
    def bprop(self, input_data, grad_output):
        # orig_input_data_shape = input_data.shape
        # high_dimension_input = input_data.ndim > 2
        #
        # # Reshape input and grad_output
        # if high_dimension_input:
        #     input_data  = input_data.reshape(input_data.shape[0], -1)
        #     grad_output = grad_output.reshape(grad_output.shape[0], -1)

        # self.weight.grad = self.weight.grad + np.dot(input_data.T, grad_output)
        # self.bias.grad   = self.bias.grad + grad_output.sum(axis=0)
        self.weight.grad = np.dot(input_data.T, grad_output)
        self.bias.grad   = grad_output.sum(axis=0)
        self.grad_input  = np.dot(grad_output, self.weight.D.T)

        # if high_dimension_input:
        #     self.grad_input = self.grad_input.reshape(orig_input_data_shape)

        return self.grad_input

    def update(self, params):
        self.weight.update(params)
        self.bias.update(params)

    def share(self, m):
        self.weight = m.weight
        self.bias = m.bias
Exemplo n.º 4
0
def setq_weight_detail():
    if request.method == 'POST':
        get_data = json.loads(request.get_data(as_text=True))
        param = {'setq_id': get_data['setq_id']}
        w = Weight()
        data = w.allweight(param)
        if data == None:
            resData = {'resCode': 1, 'data': [], 'message': '未查询到该问题集合的权重记录'}
            return jsonify(resData)
        resData = {'resCode': 0, 'data': data, 'message': '查询成功'}
        return jsonify(resData)
    else:
        resData = {"resCode": 1, "data": [], "message": '请求方式错误'}
        return jsonify(resData)
Exemplo n.º 5
0
 def __init__(self, *pargs):
     self.weights = None
     self.input = 0.0
     self.sigmoid = 1
     self.bias = 1.0
     self.error = 0.0
     self.learning_rate = 0.01
     self.output = None
     if pargs:
         inputs, rand = pargs
         self.weights = []
         for input in inputs.get_layer():
             w = Weight()
             w.input = input
             w.value = rand.uniform(-1, 1)
             self.weights.append(w)
Exemplo n.º 6
0
 def __init__(self,
              control_directory=".",
              control_file="hypoDD.inp",
              cc_dt_input="",
              ct_dt_input="dt.ct",
              initial_hypocenters="event.dat",
              station_input="station.dat",
              initial_hypocenters_output="hypoDD.loc",
              relocated_hypocenters_output="hypoDD.reloc",
              station_residual_output="hypoDD.sta",
              data_residual_output="hypoDD.res",
              takeoff_angle_output="hypoDD.src",
              idat=3,
              ipha=3,
              dist=400,
              obscc=0,
              obsct=8,
              istart=2,
              isolv=2,
              weights=[
                  Weight(niter=10,
                         wtccp=-9,
                         wtccs=-9,
                         wrcc=-9,
                         wdcc=-9,
                         wtctp=1,
                         wtcts=0.5,
                         wrct=3,
                         wdct=3,
                         damp=10)
              ],
              velocity_model=VelocityModel(),
              cid=0,
              evid=[]):
     """Initialization method for the HypoDDControl object.
     """
     self.control_directory = control_directory
     self.control_file = control_file
     self.cc_dt_input = cc_dt_input
     self.ct_dt_input = ct_dt_input
     self.initial_hypocenters = initial_hypocenters
     self.station_input = station_input
     self.initial_hypocenters_output = initial_hypocenters_output
     self.relocated_hypocenters_output = relocated_hypocenters_output
     self.station_residual_output = station_residual_output
     self.data_residual_output = data_residual_output
     self.takeoff_angle_output = takeoff_angle_output
     self.idat = idat
     self.ipha = ipha
     self.dist = dist
     self.obscc = obscc
     self.obsct = obsct
     self.istart = istart
     self.isolv = isolv
     self.weights = weights
     self.velocity_model = velocity_model
     self.cid = cid
     self.evid = evid
    def online_learning(self):
        count = 0

        """ initinalize """
        for value in self.feature.values():
            split_word = value.split(' ')
            [self.weight.update({self.flabel + word: 0}) for word in split_word]
        cfeature = FeatureCreator()

        """ update weight """
        while self.iteration >= count:
            count = count + 1
            for key, value in self.feature.items():
                self.phi = cfeature.create(value, self.data, self.flabel)
                self.label = TrainOnePrediction(self.weight, self.phi)
                if self.label is not key:
                    update_weight = Weight(self.weight, self.phi, key)
                    self.weight = update_weight.update()
Exemplo n.º 8
0
def new_weight():
    if request.method == 'POST':
        get_data = json.loads(request.get_data(as_text=True))
        param = {
            'user_id': get_data['u_id'],
            'setq_id': get_data['q_id'],
            'weight1': get_data['w1'],
            'weight2': get_data['w2']
        }
        w = Weight()
        data = w.new_weight(param)
        if data == True:
            resData = {"resCode": 0, "data": data, "message": '权重已更新'}
            return jsonify(resData)
        resData = {"resCode": 1, "data": [], "message": '更新失败'}
        return jsonify(resData)
    else:
        resData = {"resCode": 1, "data": [], "message": '请求方式错误'}
        return jsonify(resData)
Exemplo n.º 9
0
 def getWeight(self, intLumi=None):
     # if intLumi is None:
     #    intLumi = Weight.FBINV
     #COLIN THIS WEIGHT STUFF IS REALLY BAD!!
     # use the existing Weight class or not? guess so...
     return Weight(genNEvents=self.nGenEvents,
                   xSection=self.xSection,
                   intLumi=self.intLumi,
                   genEff=1 / self.effCorrFactor,
                   addWeight=self.addWeight)
Exemplo n.º 10
0
 def convert_unit(self, value, input_unit, output_unit):
     if self.measurement is 'length':
         return Length(value, input_unit, output_unit).convert()
     if self.measurement is 'temperature':
         return Temperature(value, input_unit, output_unit).convert()
     if self.measurement is 'area':
         return Area(value, input_unit, output_unit).convert()
     if self.measurement is 'volume':
         return Volume(value, input_unit, output_unit).convert()
     if self.measurement is 'weight':
         return Weight(value, input_unit, output_unit).convert()
     return "Not a valid measurement is entered! Select from : length, temperature, volume, area, weight"
Exemplo n.º 11
0
    def __init__(self, name=None, surname=None, username=None, passwd=None, email=None, height=None, weight=None,
                 state='metric'):
        """
        Constructor for a first time user if username is given, or an empty constructor otherwise
        :param name: name
        :param surname: surname
        :param username: username -REQUIRED FOR A NEW USER @TODO: add name, surname and email to required parameters
        :param email: email
        :param height: height @TODO: add a height class for imperial/metric conversion on the fly
        :param weight: weight Class already implemented, @TODO: Test thoroughly
        :param state: metric/imperial measurement standard @TODO: Rename/Refactor to something more descriptive
        @TODO: Reorganize the code into smaller, more readable parts
        @TODO: Detailed comments
        """
        if username is not None:
            self.name = name
            self.surname = surname
            self.username = username
            self.uID = uuid.uuid4()
            self.email = email
            if len(passwd) < 8:
                raise Exception("Password too short. Minimum length is 8 characters")
            pwd = hash_password(passwd)
            salt = pwd[:64]
            stPwd = pwd[64:]

            self.DBInfo = DBInfo(uID=self.uID)
            conn = create_connection("Acc.db")
            create_table(conn, create_commands)
            cur = conn.cursor()
            cur.execute(arg, (name, surname, username, salt, stPwd, email, height, weight, state, str(self.uID)))
            conn.commit()
            if height is None:
                self.height = -1
            else:
                self.height = height
            if weight is None:
                self.weight = None
            else:
                self.weight = Weight(weight, state=state)
Exemplo n.º 12
0
 def getWeight(self, intLumi=None):
     '''Returns the normalization weight for a given integrated luminosity
     
     '''
     # if intLumi is None:
     #    intLumi = Weight.FBINV
     #COLIN THIS WEIGHT STUFF IS REALLY BAD!!
     # use the existing Weight class or not? guess so...
     return Weight(genNEvents=self.nGenEvents,
                   xSection=self.xSection,
                   intLumi=self.intLumi,
                   genEff=1 / self.effCorrFactor,
                   addWeight=self.addWeight)
    def create_weights(nodes, num_of_features, hidden_nodes):
        weights = []

        total_layers = 1 + len(hidden_nodes) + 1

        weight_index = 0

        for i in range(total_layers - 1):
            for j in range(len(nodes)):
                if nodes[j].get_level() == i:
                    for k in range(len(nodes)):
                        if nodes[k].get_level() == i + 1:
                            if nodes[k].get_is_bias_unit() == False:
                                #there is a connection from nodes [j] to nodes [k]
                                #--------------------------------
                                range_min = 0
                                range_max = 1
                                init_epsilon = math.sqrt(6) / (
                                    math.sqrt(num_of_features + 1))
                                rand = range_min + (
                                    range_max - range_min) * random.random()
                                rand = rand * (2 * init_epsilon) - init_epsilon

                                #--------------------------------
                                weight = Weight()  # initialise weight
                                weight.set_weight_index(weight_index)
                                weight.set_from_index(nodes[j].get_index())
                                weight.set_to_index(nodes[k].get_index())
                                weight.set_value(
                                    rand)  # use random starting value
                                weight_index = weight_index + 1

                                weights.append(weight)

                                print("from " + str(nodes[j].get_label()) +
                                      " to " + str(nodes[k].get_label()) +
                                      ": " + str(rand))
        return weights
Exemplo n.º 14
0
def calc_info():
    for doc in read_doc('corpus/jisuanji'):
        cat_info['jsj'] += 1
        for word in jieba.cut(doc, cut_all=False):
            word_info[word]['jsj'] += 1

    for doc in read_doc('corpus/huanjing'):
        cat_info['hj'] += 1
        for word in jieba.cut(doc, cut_all=False):
            word_info[word]['hj'] += 1

    wt = Weight(cat_info, word_info)

    word_list = []
    for word, score in sorted(wt.ECE_ID4().items(),
                              key=lambda x: x[1],
                              reverse=True):
        word_list.append(word)

    word_dict = {w: i for i, w in enumerate(word_list)}
    fp = open('data/info.pk', 'wb')
    pickle.dump(word_list, fp)
    pickle.dump(word_dict, fp)
    return word_list, word_dict
Exemplo n.º 15
0
def report_weight_reading(body):
    """ Receives a weight reading """

    session = DB_SESSION()

    w = Weight(body['user_id'],
               body['user_name'],
               body['weight'],
               body['timestamp'])
    session.add(w)

    session.commit()
    session.close()

    logger.debug(f"Stored event Weight request with a unique id of {body['user_id']}")
Exemplo n.º 16
0
def report_weight(body):

    session = DB_SESSION()

    wt = Weight(body['client_id'], body['device_id'], body['weight'],
                body['timestamp'])

    session.add(wt)

    session.commit()
    session.close()

    logger.debug(("DEBUG: Stored event Weight request with a unique id of " +
                  str(body['client_id'])))

    return NoContent, 201
Exemplo n.º 17
0
 def __init__(self, in_dim, out_dim):
     super(Linear, self).__init__()
     self.in_dim = in_dim
     self.out_dim = out_dim
     self.weight = Weight((in_dim, out_dim))
     self.bias = Weight((1, out_dim))
Exemplo n.º 18
0
 def getWeight(self, intLumi=None):
     return Weight(genNEvents=-1,
                   xSection=None,
                   genEff=-1,
                   intLumi=self.intLumi,
                   addWeight=1.)
Exemplo n.º 19
0
 def connect(self, next_neuron) -> None:
     new_weight = Weight(input_neuron=self, output_neuron=next_neuron)
     self.weights.append(new_weight)
     return new_weight
    def createConnection(self, inputs, hidden_layers, outputs, nodes):

        total_layers = 1 + len(hidden_layers) + 1

        # iterate over all layers
        for i in range(total_layers - 1):
            #print ("i = ", i)
            # iterante over all nodes
            for j in range(len(nodes)):
                # find node located in layer i
                if nodes[j].getLayerNumber() == i:
                    # iterate over all nodes
                    for k in range(len(nodes)):
                        # if k'th node is in the next layer (as that of j'th node)
                        if nodes[k].getLayerNumber() == i + 1:
                            # and if k'th node is not a bias node
                            if nodes[k].getIsBiasUnit() == False:
                                # output of j'th node goes to the input of k'th node
                                weight = Weight()
                                weight.setIndex(self.weight_index)
                                weight.setFromNode(nodes[j].getIndex())
                                weight.setToNode(nodes[k].getIndex())
                                weight.setValue(self.generateRand(inputs))

                                self.weight_index = self.weight_index + 1
                                self.weights.append(weight)

                                print("Weight from " +
                                      str(nodes[j].getLabel()) + " to " +
                                      str(nodes[k].getLabel()) + " ---> " +
                                      str(weight.getValue()))

        return self.weights
Exemplo n.º 21
0
from u_net import *
import glob
from os import listdir
from os.path import isfile, join

orig_width = 340
orig_height = 260

threshold = 0.5

weights_dir = 'weights/'

onlyfiles = [f for f in listdir(weights_dir) if isfile(join(weights_dir, f))]
for counter, value in enumerate(onlyfiles):
    try:
        w = Weight(value)
        print('%d - %s' % (counter, value))
    except:
        print('%d - NOT VALID %s' % (counter, value))

index_weights = int(input('Which weights open? ') or '0')

w = Weight(onlyfiles[index_weights])
weights = w.name
params = w.params

input_size = params['inputsize']
input_shape = (input_size, input_size, 3)

if params['net'] == 'normal':  # normal
    input_size, model = get_unet_128(input_shape=input_shape)
Exemplo n.º 22
0
 def __init__(self, in_dim, out_dim):
     super(Linear, self).__init__()
     self.in_dim  = in_dim
     self.out_dim = out_dim
     self.weight  = Weight((in_dim, out_dim))
     self.bias    = Weight((1, out_dim))
Exemplo n.º 23
0
class Account():
    """
    Main class for now
    """

    def __init__(self, name=None, surname=None, username=None, passwd=None, email=None, height=None, weight=None,
                 state='metric'):
        """
        Constructor for a first time user if username is given, or an empty constructor otherwise
        :param name: name
        :param surname: surname
        :param username: username -REQUIRED FOR A NEW USER @TODO: add name, surname and email to required parameters
        :param email: email
        :param height: height @TODO: add a height class for imperial/metric conversion on the fly
        :param weight: weight Class already implemented, @TODO: Test thoroughly
        :param state: metric/imperial measurement standard @TODO: Rename/Refactor to something more descriptive
        @TODO: Reorganize the code into smaller, more readable parts
        @TODO: Detailed comments
        """
        if username is not None:
            self.name = name
            self.surname = surname
            self.username = username
            self.uID = uuid.uuid4()
            self.email = email
            if len(passwd) < 8:
                raise Exception("Password too short. Minimum length is 8 characters")
            pwd = hash_password(passwd)
            salt = pwd[:64]
            stPwd = pwd[64:]

            self.DBInfo = DBInfo(uID=self.uID)
            conn = create_connection("Acc.db")
            create_table(conn, create_commands)
            cur = conn.cursor()
            cur.execute(arg, (name, surname, username, salt, stPwd, email, height, weight, state, str(self.uID)))
            conn.commit()
            if height is None:
                self.height = -1
            else:
                self.height = height
            if weight is None:
                self.weight = None
            else:
                self.weight = Weight(weight, state=state)

    def logIn(self, username, pwd):
        """
        Logs in a user
        :param username: username
        :param pwd: password
        :return: None @TODO: Maybe return True/False?
                            (Exceptions implemented, don't think it's worth doing)
        @TODO: Detailed comments
        """
        conn = create_connection("Acc.db")
        cur = conn.cursor()
        try:
            cur.execute("SELECT * FROM Accounts WHERE Accounts.username=?", (username,))
        except sqlite3.OperationalError:
            raise Exception("User doesn't exist")
        rows = cur.fetchall()
        for row in rows:
            salt = row[4]
            stPwd = row[5]
            pwdhash = hashlib.pbkdf2_hmac('sha512', pwd.encode('utf-8'), salt.encode('ascii'), 100000)
            pwdhash = binascii.hexlify(pwdhash).decode('ascii')
            print()
            if pwdhash != stPwd:
                raise Exception("Invalid password")

            self.name = row[1]
            self.surname = row[2]
            self.username = row[3]
            self.email = row[6]
            self.height = row[7]
            self.weight = Weight(row[8], row[9])
            self.uID = row[10]

        self.DBInfo = DBInfo(self.uID)

    def __repr__(self):
        """
        String representation of the Account class
        :return: Returns the uID for now @TODO: A nice log for the developer maybe
        """
        return str(self.uID)

    def measure(self, wght):
        """
        Measure current body mass
        :param wght: New mass in preferred unit @TODO: Test with different standard
        :return: None
        """
        self.weight.set(wght)
        self.DBInfo.add(wght)

    @staticmethod
    def resetPassword(email):
        """
        STATIC METHOD
        Resets the password for the given email after verification
        :param email: email
        :return:
        @TODO: Improve the email server/gmail account handling (NO HARDCODED PASSWORDS)
        @TODO: Detailed comments
        """

        port = 465  # For SSL
        # Create a secure SSL context
        context = ssl.create_default_context()

        strchk = get_random_string(randint(5, 10))
        """
        FOR THIS TO WORK YOU HAVE TO CREATE THE FILE IN conf/application.yml in this format:
        user:
            email: [email protected]
            password: YOURPASSWORD
        """
        conf = yaml.safe_load(open('conf/application.yml'))
        senderemail = conf['user']['email']
        senderpwd = conf['user']['password']
        with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
            server.login(senderemail, senderpwd)
            server.sendmail("*****@*****.**", email, "Subject: Password recovery string: \n\n" + strchk)

        chckinput = input("Input the code that was sent to your email: ")
        if strchk == chckinput:
            newpwd = input("Enter your new password: "******"Password too short. Minimum length is 8 characters")
            pwd = hash_password(newpwd)
            salt = pwd[:64]
            stPwd = pwd[64:]
            conn = create_connection("Acc.db")
            create_table(conn, create_commands)
            cur = conn.cursor()
            cur.execute("UPDATE Accounts SET salt = ?, pwd = ? WHERE email = ?", (salt, stPwd, email))
            conn.commit()
            cur.close()
        else:
            raise Exception("Wrong recovery code")

    def resetEmail(self, newmail):
        """
        Resets the email
        :param newmail: New email
        :return: None
        @TODO: Confirmation of email
        """
        conn = create_connection("Acc.db")
        create_table(conn, create_commands)
        cur = conn.cursor()
        cur.execute("UPDATE Accounts set email = ? WHERE username = ?", (newmail, self.username))
        conn.commit()
        cur.close()

    def display(self):
        """
        Displays the collected data in a chart
        :return: None
        @TODO: Implement this in the GUI
        @TODO: Different types of charts?
        @TODO: Detailed comments
        """
        import matplotlib.pyplot as plt
        wghts = self.DBInfo.allWeights()
        w = []
        for i in wghts:
            w.append(i[0])
            print(i)
        dates = self.DBInfo.allDates()
        k = []
        import numpy as np
        for i in dates:
            k.append(i[0])
            # i = i[0].split()
            # k.append(i[1][3:])
            print(type(i))

        print(k)
        plt.plot(k, w, linestyle='-', linewidth=1, color='red')
        plt.title(self.username)
        # plt.xticks(np.arange(0, 60, step=5))
        plt.show()
Exemplo n.º 24
0
from weight import Weight
from graph import Graph

data_file = 'data.json'
w = Weight('data.json')
date = w.get_date()
months = w.months

while True:
    w.cls()
    w.show_records(date)

    print('___________________________________________________')
    print('a=add record; s=show records; g=show graph; q=quit')

    i = input('>> ').lower()

    # Add record
    if i == 'a':
        # w.cls()
        try:
            record = float(input('Add weight for today: '))
            w.add_record(record, date)
        except ValueError as e:
            print('Enter a number, not a string.')

    elif i == 's':
        for i in range(len(w.months)):
            print(f'{i+1}. {w.months[i]}')

        select_month = int(input('\nChoose month: '))
Exemplo n.º 25
0
def project():
    if request.method == 'POST':
        get_data = json.loads(request.get_data(as_text=True))
        # 1.准备数据
        # 具体来说,获取数据库中所有该问题集合的问题,和所有用户的回答
        # q_list[]
        # ans1[]
        # ans2[]
        # ans1[i][j] 问题i 用户j
        # weight[i] 用户i的权重
        user_list = []
        q_list = []
        ans1 = []
        ans2 = []
        # 1.1找出所有问题id
        param = {'id_setq': get_data['setq_id']}
        q = Q()
        data = q.allq_id(param)
        for i in data:
            q_list.append(i['idq'])
            ans1.append([])
            ans2.append([])
        print('q_list = ', q_list)
        # 1.2根据问题id确定回答问题的用户id
        # for i in range(len(q_list)):
        param = {'id_q': q_list[0]}
        a = Ans()
        data = a.allans_userid(param)

        for item in data:
            if item['user_id'] not in user_list:
                user_list.append(item['user_id'])
        print('user_list = ', data)
        # 1.3对应问题id和用户id的所有回答,ans1和ans2
        for i in range(len(q_list)):
            for j in user_list:
                param = {'id_q': q_list[i], 'id_user': j}
                a = Ans()
                data = a.allans_q_user(param)
                for item in data:
                    ans1[i].append(item['ans_one'])
                    ans2[i].append(item['ans_two'])
        print('ans1 = ', ans1)
        print('ans2 = ', ans2)

        # 2.聚合结果
        # MV-one
        # MV-two
        Data = []

        q_MV_one = MV(ans1)
        Data.append(q_MV_one)

        for i in range(len(q_list)):
            param = {'id_q': q_list[i], 'ans': q_MV_one[i]}
            q = Q()
            q.set_q_MV_one(param)

        q_MV_two = MV(ans2)
        Data.append(q_MV_two)

        for i in range(len(q_list)):
            param = {'id_q': q_list[i], 'ans': q_MV_two[i]}
            q = Q()
            q.set_q_MV_two(param)
        # TD-one
        # TD-two
        # TD要返回对应的weight列表
        q_TD_one, weight_one = TD(user_list, q_list, ans1)
        Data.append(q_TD_one)

        for i in range(len(q_list)):
            param = {'id_q': q_list[i], 'ans': q_TD_one[i]}
            q = Q()
            q.set_q_TD_one(param)

        q_TD_two, weight_two = TD(user_list, q_list, ans2)
        Data.append(q_TD_two)

        for i in range(len(q_list)):
            param = {'id_q': q_list[i], 'ans': q_TD_two[i]}
            q = Q()
            q.set_q_TD_two(param)
        # 更新权重
        for i in range(len(user_list)):
            param = {
                'user_id': user_list[i],
                'setq_id': get_data['setq_id'],
                'weight1': weight_one[i],
                'weight2': weight_two[i]
            }
            w = Weight()
            w.new_weight(param)

        resData = {"resCode": 0, "data": Data, "message": '返回聚合结果'}
        return jsonify(resData)
Exemplo n.º 26
0
class HypoDDControl:
    """Control parameters for hypoDD.

    Attributes:
    control_directory: The directory where the control file is located.
    control_file: The name of the control file.
    cc_dt_input: Filename of cross-corr diff. time input.
    ct_dt_input: Filename of catalog travel time input.
    initial_hypocenters: Filename of initial hypocenter input.
    station_input: Filename of station input.
    initial_hypocenters_output: Filename of initial hypocenter output.
    relocated_hypocenters_output: Filename of relocated hypocenter output.
    station_residual_output: Filename of station residual output.
    data_residual_output: Filename of data residual output.
    takeoff_angle_output: Filename of takeoff angle output.
    idat: Data type: 1 = cross correlation data only; 2 = absolute (catalog)
          data only; 3 = x-corr & catalog.
    ipha: Phase: 1 = P-wave; 2 = S-wave; 3 = P- & S-wave.
    dist: Max. distance between centroid of event cluster and stations.
    obscc, obsct: Min. number of x-corr, catalog links per event pair to form a
                  continuous cluster. 0 = no clustering performed. If IDAT = 3,
                  the sum of OBSCC and OBSCT is taken and used for both. 
    istart: Initial locations: 1 = start from cluster centroid; 2 = start from
            catalog locations.
    isolv: Least squares solution: 1 = singular value decomposition (SVD);
           2 = conjugate gradients (LSQR).
    weights: Data weighting by iteration. See class Weight.
    velocity_model: The velocity model to be used. See class VelocityModel.
    cid: Index of cluster to be relocated (0 = all).
    evid: ID of events to be relocated (8 per line). Blank for all events.
          The ID numbers are in free format.
    """

    control_directory = "."
    control_file = "hypoDD.inp"
    cc_dt_input = ""
    ct_dt_input = "dt.ct"
    initial_hypocenters = "event.dat"
    station_input = "station.dat"
    initial_hypocenters_output = "hypoDD.loc"
    relocated_hypocenters_output = "hypoDD.reloc"
    station_residual_output = "hypoDD.sta"
    data_residual_output = "hypoDD.res"
    takeoff_angle_output = "hypoDD.src"
    idat = 3
    ipha = 3
    dist = 400
    obscc = 0
    obsct = 8
    istart = 2
    isolv = 2
    weights = [
        Weight(niter=10,
               wtccp=-9,
               wtccs=-9,
               wrcc=-9,
               wdcc=-9,
               wtctp=1,
               wtcts=0.5,
               wrct=3,
               wdct=3,
               damp=10)
    ]
    velocity_model = VelocityModel()
    cid = 0
    evid = []

    def __init__(self,
                 control_directory=".",
                 control_file="hypoDD.inp",
                 cc_dt_input="",
                 ct_dt_input="dt.ct",
                 initial_hypocenters="event.dat",
                 station_input="station.dat",
                 initial_hypocenters_output="hypoDD.loc",
                 relocated_hypocenters_output="hypoDD.reloc",
                 station_residual_output="hypoDD.sta",
                 data_residual_output="hypoDD.res",
                 takeoff_angle_output="hypoDD.src",
                 idat=3,
                 ipha=3,
                 dist=400,
                 obscc=0,
                 obsct=8,
                 istart=2,
                 isolv=2,
                 weights=[
                     Weight(niter=10,
                            wtccp=-9,
                            wtccs=-9,
                            wrcc=-9,
                            wdcc=-9,
                            wtctp=1,
                            wtcts=0.5,
                            wrct=3,
                            wdct=3,
                            damp=10)
                 ],
                 velocity_model=VelocityModel(),
                 cid=0,
                 evid=[]):
        """Initialization method for the HypoDDControl object.
        """
        self.control_directory = control_directory
        self.control_file = control_file
        self.cc_dt_input = cc_dt_input
        self.ct_dt_input = ct_dt_input
        self.initial_hypocenters = initial_hypocenters
        self.station_input = station_input
        self.initial_hypocenters_output = initial_hypocenters_output
        self.relocated_hypocenters_output = relocated_hypocenters_output
        self.station_residual_output = station_residual_output
        self.data_residual_output = data_residual_output
        self.takeoff_angle_output = takeoff_angle_output
        self.idat = idat
        self.ipha = ipha
        self.dist = dist
        self.obscc = obscc
        self.obsct = obsct
        self.istart = istart
        self.isolv = isolv
        self.weights = weights
        self.velocity_model = velocity_model
        self.cid = cid
        self.evid = evid

    def write_control_file(self):
        print "preparing hypoDD control"
        print "working directory is {}".format(self.control_directory)
        full_filename = "{}/{}".format(self.control_directory,
                                       self.control_file)
        print "writing ph2dt control file: {}".format(full_filename)

        nlay = len(self.velocity_model.layers)
        nset = len(self.weights)

        with open(full_filename, "w") as f:
            control_file_format_1 = (
                "* {}\n"
                "*--- INPUT FILE SELECTION\n"
                "* filename of cross-corr diff. time input "
                "(blank if not available):\n"
                "{}\n"
                "* filename of catalog travel time input "
                "(blank if not available):\n"
                "{}\n"
                "* filename of initial hypocenter input:\n"
                "{}\n"
                "* filename of station input:\n"
                "{}\n"
                "*\n"
                "*--- OUTPUT FILE SELECTION\n"
                "* filename of initial hypocenter output "
                "(if blank: output to hypoDD.loc):\n"
                "{}\n"
                "* filename of relocated hypocenter output "
                "(if blank: output to hypoDD.reloc):\n"
                "{}\n"
                "* filename of station residual output "
                "(if blank: no output written):\n"
                "{}\n"
                "* filename of data residual output "
                "(if blank: no output written):\n"
                "{}\n"
                "* filename of takeoff angle output "
                "(if blank: no output written):\n"
                "{}\n"
                "*\n"
                "*--- DATA SELECTION:\n"
                "* IDAT IPHA DIST\n"
                "{} {} {}\n"
                "*\n"
                "*--- EVENT CLUSTERING:\n"
                "* OBSCC OBSCT\n"
                "{} {}\n"
                "*\n"
                "*--- SOLUTION CONTROL:\n"
                "* ISTART ISOLV NSET\n"
                "{} {} {}\n"
                "*\n"
                "*--- DATA WEIGHTING AND REWEIGHTING:\n"
                "* NITER WTCCP WTCCS WRCC WDCC WTCTP WTCTS "
                "WRCT WDCT DAMP\n")
            f.write(
                control_file_format_1.format(
                    self.control_file, self.cc_dt_input, self.ct_dt_input,
                    self.initial_hypocenters, self.station_input,
                    self.initial_hypocenters_output,
                    self.relocated_hypocenters_output,
                    self.station_residual_output, self.data_residual_output,
                    self.takeoff_angle_output, self.idat, self.ipha, self.dist,
                    self.obscc, self.obsct, self.istart, self.isolv, nset))
            control_file_format_2 = "{} {} {} {} {} {} {} {} {} {}\n"
            for weight in self.weights:
                f.write(
                    control_file_format_2.format(weight.niter, weight.wtccp,
                                                 weight.wtccs, weight.wrcc,
                                                 weight.wdcc, weight.wtctp,
                                                 weight.wtcts, weight.wrct,
                                                 weight.wdct, weight.damp))
            control_file_format_3 = ("*\n"
                                     "*--- MODEL SPECIFICATIONS:\n"
                                     "* NLAY RATIO\n"
                                     "{} {}\n"
                                     "* TOP:\n")
            f.write(
                control_file_format_3.format(nlay, self.velocity_model.ratio))
            control_file_format_4 = " {}"
            for layer in self.velocity_model.layers:
                f.write(control_file_format_4.format(layer.top))
            f.write("\n* VEL:\n".format())
            for layer in self.velocity_model.layers:
                f.write(control_file_format_4.format(layer.vel))
            control_file_format_5 = ("\n*\n"
                                     "*--- CLUSTER/EVENT SELECTION:\n"
                                     "* CID\n"
                                     "{}\n")
            f.write(control_file_format_5.format(self.cid))
            f.write("* ID\n".format())
            n = len(self.evid)
            k = n // 8
            m = n - 8 * k
            control_file_format_6 = "{}\n"
            for i in range(1, k + 1):
                f.write(
                    control_file_format_6.format(" ".join(
                        str(x) for x in self.evid[i * 8 - 8:i * 8])))
            f.write(
                control_file_format_6.format(" ".join(
                    str(x) for x in self.evid[n - m:n])))