text:
import tensorflow as tf
import pandas as pd
import numpy as np
import time
from flask import Flask, jsonify, request

tf.reset_default_graph()
np.random.seed(11)

total_no_of_users = 30 #138494
total_no_of_movies = 259 #131263

batch_size = 50 # Batch size
k = 5 # No. of latent factors
epochs = 100 # No. of epochs

all_movies = []

movie_to_id = {}
id_to_movie = {}

movies_rated_by_user = {}

movies = pd.read_csv("C://Users//sorablaze_11//Desktop//RecSys//movielens//ml-20m//newdata//DDShows.csv")
# Load data from given path using pandas.
data = pd.read_csv("C://Users//sorablaze_11//Desktop//RecSys//movielens//ml-20m//newdata//DDRatings.csv")
# Total no. of ratings
rows = len(data)
# Randomly shuffling the order of the ratings rows.
data = data.iloc[np.random.permutation(rows)].reset_index(drop=True)
# Declaring our test-train split percentage.
for _, row in movies.iterrows():
    id_to_movie[int(row[0])] = row[1]
    movie_to_id[row[1]] = int(row[0])
    all_movies.append(row[0])

for _ in range(0, total_no_of_users):
    movies_rated_by_user[_] = []

for _, row in data.iterrows():
    movies_rated_by_user[int(row[0])].append(int(row[1]))

print('Loading of data done.')

imported_meta = tf.train.import_meta_graph('./save/model.meta')
init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)
imported_meta.restore(sess,  './save/model')
output = tf.get_collection('output_')[0]

app = Flask(__name__)

@app.route('/api', methods=['POST'])
def getRecommendations():
    global movies_rated_by_users
    global id_to_movie
    global movie_to_id
    global all_movies
    userId = request.get_json(force=True)
    userId = userId['userId']
    movies = []
    for _ in all_movies:
        if _ not in movies_rated_by_user[userId]:
            movies.append(_)
    # movies = [_ for _ in all_movies if _ not in movies_rated_by_user[userId]]
    users = np.array([userId] * len(movies))
    movies = np.array(movies)
    pred_batch = sess.run(output, feed_dict={'id_user:0': users, 'id_movie:0': movies})
    print('length of predicted batch', len(pred_batch))
    pred_batch = np.clip(pred_batch, 1.0, 5.0)
    ratings = [[movies[_], pred_batch[_]] for _ in range(pred_batch.shape[0])]
    ratings = sorted(ratings, key=lambda x : x[1], reverse=True)
    ratings = ratings[:10]
    print('Movies to be recommender:')
    for _ in range(10):
        print(id_to_movie[ratings[_][0]], ' ', ratings[_][1])
    print(type(id_to_movie[ratings[0][0]]))
    optdict = []
    for _ in range(10):
        temp = id_to_movie[ratings[_][0]] + ' - ' + str(ratings[_][0])
        optdict.append({'movie_name_and_id' : temp})
    return jsonify(optdict)

@app.route('/addratings', methods=['POST'])
def addratings():
    global movies_rated_by_user
    inp = request.get_json(force=True)
    userId = inp['userId']
    movieId = inp['movieId']
    rating = inp['rating']
    movies_rated_by_user[userId].append(movieId)
    with open('C://Users//sorablaze_11//Desktop//RecSys//movielens//ml-20m//newdata//DDRatings.csv', 'a') as f:
        f.write(str(userId) + ',' + str(movieId) + ',' + str(rating) + '\n')
        x = [50]
    return jsonify(x)

if __name__ == '__main__':
    app.run(port=9000, debug=True)


text:
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 25 20:35:03 2017

@author: David
"""
from __future__ import print_function
import datetime
import glob
import logging
import os
import sys
import time
import subprocess
import picamera
import picamera.array
import numpy as np
import pyexiv2
from imutils.video import WebcamVideoStream
from imutils.video import FPS
import argparse
import imutils
import cv2
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from fractions import Fraction
from subprocess import call
from flask import Flask, send_file,request, render_template,send_from_directory
from pymongo import MongoClient
from bson.json_util import dumps

app=Flask(__name__)

MONGODBCLIENT = 'bird-db.local'
mypath = os.path.abspath(__file__)  # Find the full path of this python script
baseDir = os.path.dirname(mypath)  # get the path location only (excluding script name)
baseFileName = os.path.splitext(os.path.basename(mypath))[0]
progName = os.path.basename(__file__)
logFilePath = os.path.join(baseDir, baseFileName + ".log")
print("----------------------------------------------------------------------------------------------")
# print("%s %s" %( progName, progVer ))

rpicam = WebcamVideoStream(0)
webcam = WebcamVideoStream(1)
configFilePath = os.path.join(baseDir, "config.py")

if not os.path.exists(configFilePath):
    print("ERROR - Cannot Import Configuration Variables. Missing Configuration File %s" % ( configFilePath ))
    quit()
else:
    # Read Configuration variables from config.py file
    print("Importing Configuration Variables from File %s" % ( configFilePath ))
    from config import *

def writeTextToImage(imagename, datetoprint):
    # function to write date/time stamp directly on top or bottom of images.
    FOREGROUND = ( 255, 255, 255 )  # rgb settings for white text foreground
    textColour = "White"

    # centre text and compensate for graphics text being wider
    x = int((imageWidth/2) - (len(imagename)*2))
    if showTextBottom:
        y = (imageHeight - 50)  # show text at bottom of image
    else:
        y = 10  # show text at top of image
    TEXT = imageNamePrefix + datetoprint
    font_path = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
    font = ImageFont.truetype(font_path, showTextFontSize, encoding='unic')
    text = TEXT.decode('utf-8')

    # Read exif data since ImageDraw does not save this metadata
    img = Image.open(imagename)
    metadata = pyexiv2.ImageMetadata(imagename)
    metadata.read()

    draw = ImageDraw.Draw(img)
    # draw.text((x, y),"Sample Text",(r,g,b))
    draw.text(( x, y ), text, FOREGROUND, font=font)
    img.save(imagename)
    metadata.write()    # Write previously saved exif data to image file
    logging.info("Added %s Text[%s] on %s", textColour, datetoprint, imagename)
    return

def getImageName(path, prefix):
    # build image file names by number sequence or date/time

    rightNow = datetime.datetime.now()
    filename = "%s/%s%04d%02d%02d-%02d%02d%02d.jpg" % ( path, prefix ,rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second)
    return filename

def getVideoName(path, prefix):
    # build image file names by number sequence or date/time

    rightNow = datetime.datetime.now()
    filename = "%s/%s%04d%02d%02d-%02d%02d%02d.h264" % ( path, prefix ,rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second)
    return filename

def takeDayImage__(filename):
    # Take a Day image using exp=auto and awb=auto
    with picamera.PiCamera() as camera:
            camera.resolution = (imageWidth, imageHeight)
            camera.vflip = imageVFlip
            camera.hflip = imageHFlip
            camera.rotation = imageRotation #Note use imageVFlip and imageHFlip variables
            time.sleep(0.2)
            camera.capture(filename, use_video_port=useVideoPort)
    logging.info("Size=%ix%i exp=auto awb=auto %s" % (imageWidth, imageHeight, filename))
    return

def takeDayImage(filename):
    ''' grabs the frame from teh raspi camera'''
    frame = rpicam.read()
    cv2.imwrite(filename, frame)

def takeWebcamImage__(filename):
    call(["fswebcam", "-d","/dev/video0", "-r", "640x480", "--no-banner", filename])

def takeWebcamImage(filename):
    '''Grabs an image fromt eh webcam stream'''
    frame = webcam.read()
    cv2.imwrite(filename, frame)

def takeVideo(filename):
    # Take a short motion video if required
    logging.info("Size %ix%i for %i sec %s" % (imageWidth, imageHeight, motionVideoTimer, filename))
    if motionVideoOn:
        with picamera.PiCamera() as camera:
            camera.resolution = (imageWidth, imageHeight)
            camera.vflip = imageVFlip
            camera.hflip = imageHFlip
            camera.rotation = imageRotation #Note use imageVFlip and imageHFlip variables
            if showDateOnImage:
                rightNow = datetime.datetime.now()
                dateTimeText = " Started at %04d-%02d-%02d %02d:%02d:%02d " % (rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second)
                camera.annotate_text_size = showTextFontSize
                camera.annotate_foreground = picamera.Color('black')
                camera.annotate_background = picamera.Color('white')
                camera.annotate_text = dateTimeText
            camera.start_recording(filename)
            camera.wait_recording(motionVideoTimer)
            camera.stop_recording()
        # This creates a subprocess that runs convid.sh with the filename as a parameter
        try:
            convid = "%s/convid.sh %s" % ( baseDir, filename )
            proc = subprocess.Popen(convid, shell=True,
                             stdin=None, stdout=None, stderr=None, close_fds=True)
        except IOError:
            print("subprocess %s failed" %s ( convid ))
        else:
            print("unidentified error")
        createSyncLockFile(filename)
    return

@app.route('/')
def hello():
    return "Hello World!"

@app.route('/take-image')
def take_image():
    filename = getImageName(motionDir, imageNamePrefix)
    daystamp = datetime.datetime.now().strftime('%Y%m%d')
    tag = request.args.get('tag')
    takeDayImage(filename)
    revfn = getImageName(motionDir, 'reverse')
    takeWebcamImage(revfn)
    #writeTextToImage(filename, str(datetime.datetime.now()))
    if tag:
        db = MongoClient(MONGODBCLIENT)
        db.test.birdwatcher.insert_one({'tag':tag, 'filename':filename,
                                     'day': daystamp, 'reverse': revfn})
    return send_file(open(filename, 'rb'), mimetype='image/jpeg')

@app.route('/take-video')
def take_video():
    filename = getVideoName(motionDir, imageNamePrefix)
    takeVideo(filename)
    return take_image()

@app.route('/show-image')
def show_image():
    '''return a specific image'''
    filename=request.args.get('filename','Notfound.png')
    return send_file(open('motion/'+filename, 'rb'), mimetype='image/jpeg')

@app.route('/list-images')
def list_images():
    '''list images for a specific day'''
    daystamp = datetime.datetime.now().strftime('%Y%m%d')
    daystamp = request.args.get('day', daystamp)
    files = sorted([ x for x in os.listdir('motion') if daystamp in x ])
    day = datetime.datetime.strptime(daystamp, '%Y%m%d')
    db = MongoClient(MONGODBCLIENT).test.birdwatcher
    cursor = db.find({'day': daystamp})
    filelist = [ x for x in cursor if x['filename'][7:] in files]
    nextday = day + datetime.timedelta(days=1)
    previousday =day - datetime.timedelta(days=1)
    return render_template('filelist.html', heading = 'images for '+daystamp,
                           images=filelist, nextday=nextday.strftime('%Y%m%d'),
                           previousday=previousday.strftime('%Y%m%d'))

@app.route('/image-details')
def image_details():
    filename=request.args.get('filename')
    if filename is None:
        return render_template('Notfound.html')
    imgtime = datetime.datetime.strptime(filename, imageNamePrefix+'%Y%m%d-%H%M%S.jpg')
    td = datetime.timedelta(seconds=5.5)
    db = MongoClient(MONGODBCLIENT)

    fileinfo = db.test.birdwatcher.find_one({'filename': 'motion/'+filename})
    if fileinfo and 'tag' in fileinfo:
        cursor = db.test.birdfeeder.find({'tag': fileinfo['tag']})
    else:
         cursor = db.test.birdfeeder.find({'timestamp': {'$gte': imgtime - td, '$lte': imgtime }})
    entries = sorted([y for y in cursor],key=lambda x:x['timestamp'])
    weights = [x['weight'] for x in entries]
    changesign = 'arrived'
    change=0
    if weights:
        change = max(weights)-min(weights)
        if weights[0] > weights[-1]:
            changesign = 'departed'
    files=[x for x in sorted(os.listdir('motion')) if x[:4]=='cam1']
    fileindex = files.index(filename)
    nextfile = files[-1]
    if fileindex < len(files) -1:
        nextfile = files[fileindex + 1]
    previousfile = files[fileindex - 1]
    return render_template('imageinfo.html', filename=filename,
                           changesign=changesign, change=change, weights=entries,
                           nextfile=nextfile, previousfile=previousfile,
                           fileinfo=fileinfo, timestamp=imgtime)

@app.route('/bird-details', methods=['POST'])
def bird_details():
    '''setter for bird details'''
    picid = request.form.get('picid')
    bird = request.form.get('species')
    db = MongoClient(MONGODBCLIENT)
    db.test.birdwatcher.update({'filename': 'motion/'+picid},
                              {'$set': {'species': bird}},
                              upsert=True)

    return dumps({'species':bird,
		'id': picid} )

@app.route('/static/js/<path:path>')
def send_js(path):
    return send_from_directory('static/js', path)

if __name__=='__main__':
    #with picamera.PiCamera() as camera:
    #   camera.resolution = (imageWidth, imageHeight)
    webcam.start()
    rpicam.start()
    app.run(port=8000, host='0.0.0.0', debug=True)

ext: py

max_stars_repo_name: davidmam/birdfeeder

max_issues_repo_name: davidmam/birdfeeder

max_forks_repo_name: davidmam/birdfeeder

reason: import numpy


text:
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch

from mmcv.ops import boxes_iou3d, nms3d, nms3d_normal

@pytest.mark.skipif(
    not torch.cuda.is_available(), reason='requires CUDA support')
def test_boxes_iou3d():
    np_boxes1 = np.asarray([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 0.0],
                            [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
                            [3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 0.0]],
                           dtype=np.float32)
    np_boxes2 = np.asarray([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 0.0],
                            [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, np.pi / 2],
                            [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, np.pi / 4]],
                           dtype=np.float32)
    np_expect_ious = np.asarray([[1.0, 1.0, 1.0 / 2**0.5],
                                 [1.0 / 7, 1.0 / 7, 1.0 / 7], [0.0, 0.0, 0.0]],
                                dtype=np.float32)

    boxes1 = torch.from_numpy(np_boxes1).cuda()
    boxes2 = torch.from_numpy(np_boxes2).cuda()

    ious = boxes_iou3d(boxes1, boxes2)
    assert np.allclose(ious.cpu().numpy(), np_expect_ious, atol=1e-4)

@pytest.mark.skipif(
    not torch.cuda.is_available(), reason='requires CUDA support')
def test_nms3d():
    # test for 5 boxes
    np_boxes = np.asarray([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 0.0],
                           [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
                           [3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 0.3],
                           [3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 0.0],
                           [3.0, 3.2, 3.2, 3.0, 2.0, 2.0, 0.3]],
                          dtype=np.float32)
    np_scores = np.array([0.6, 0.9, 0.1, 0.2, 0.15], dtype=np.float32)
    np_inds = np.array([1, 0, 3])
    boxes = torch.from_numpy(np_boxes)
    scores = torch.from_numpy(np_scores)
    inds = nms3d(boxes.cuda(), scores.cuda(), iou_threshold=0.3)

    assert np.allclose(inds.cpu().numpy(), np_inds)

    # test for many boxes
    np.random.seed(42)
    np_boxes = np.random.rand(555, 7).astype(np.float32)
    np_scores = np.random.rand(555).astype(np.float32)
    boxes = torch.from_numpy(np_boxes)
    scores = torch.from_numpy(np_scores)
    inds = nms3d(boxes.cuda(), scores.cuda(), iou_threshold=0.3)

    assert len(inds.cpu().numpy()) == 176

@pytest.mark.skipif(
    not torch.cuda.is_available(), reason='requires CUDA support')
def test_nms3d_normal():
    # test for 5 boxes
    np_boxes = np.asarray([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 0.0],
                           [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
                           [3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 0.3],
                           [3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 0.0],
                           [3.0, 3.2, 3.2, 3.0, 2.0, 2.0, 0.3]],
                          dtype=np.float32)
    np_scores = np.array([0.6, 0.9, 0.1, 0.2, 0.15], dtype=np.float32)
    np_inds = np.array([1, 0, 3])
    boxes = torch.from_numpy(np_boxes)
    scores = torch.from_numpy(np_scores)
    inds = nms3d_normal(boxes.cuda(), scores.cuda(), iou_threshold=0.3)

    assert np.allclose(inds.cpu().numpy(), np_inds)

    # test for many boxes
    np.random.seed(42)
    np_boxes = np.random.rand(555, 7).astype(np.float32)
    np_scores = np.random.rand(555).astype(np.float32)
    boxes = torch.from_numpy(np_boxes)
    scores = torch.from_numpy(np_scores)
    inds = nms3d_normal(boxes.cuda(), scores.cuda(), iou_threshold=0.3)

    assert len(inds.cpu().numpy()) == 148

max_stars_repo_name: imabackstabber/mmcv

max_issues_repo_name: imabackstabber/mmcv

max_forks_repo_name: imabackstabber/mmcv


text:
"""
@author: Milena Bajic (DTU Compute)
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import psycopg2  # pip install psycopg2==2.7.7 or pip install psycopg2==2.7.7
from json import loads
import sys, os, glob
from datetime import datetime
import pickle
from json import loads
# from sshtunnel import SSHTunnelForwarder

SSH_ADDRESS = 'thinlinc.compute.dtu.dk'

# SSH_ADDRESS = 'login2.hpc.dtu.dk'

def filter_DRDtrips_by_year(DRD_trips, sel_2021=False, sel_2020=False):
    DRD_trips['Datetime'] = pd.to_datetime(DRD_trips['Created_Date'])
    DRD_trips['Year'] = DRD_trips['Datetime'].apply(lambda row: row.year)
    if sel_2020:
        DRD_trips = DRD_trips[DRD_trips['Year'] == 2020]
    elif sel_2021:
        DRD_trips = DRD_trips[DRD_trips['Year'] == 2021]
    DRD_trips.drop(['Datetime'], axis=1, inplace=True)
    return DRD_trips

def drop_duplicates(DRD_data, iri):
    # Drop duplicate columns (due to ocassical errors in database)
    DRD_data = DRD_data.T.drop_duplicates().T  #
    if iri is not None:
        iri = iri.T.drop_duplicates().T
    return DRD_data, iri

def load_GM_data(GM_TaskId, ssh_tunnel, conn_data, prod_db=False, out_dir='.', all_sensors=False,
                 add_sensors=[], load_nrows=-1):
    # Set up connection
    print("\nConnecting to PostgreSQL database to load the DRD data")

    if prod_db:
        print("\nConnecting to production database")
        db_data = conn_data['prod']
    else:
        print("\nConnecting to development database")
        db_data = conn_data['dev']

    db = db_data['database']
    username = db_data['user']
    password = db_data['password']
    host = db_data['host']
    port = db_data['port']

    # Connection
    conn = psycopg2.connect(database=db, user=username, password=password, host=host,
                            port=port)

    # quory = 'SELECT "lat", "lon" FROM "Measurements"
    # quory = 'SELECT  "lat", "lon" FROM "Measurements" WHERE "Trips"."TaskId"=\'{0}\' ORDER BY "TS_or_Distance" ASC LIMIT {1}'.format(GM_TaskId, load_nrows)
    # quory = 'SELECT  "lat", "lon" FROM ("Measurements" INNER JOIN "Trips" ON "Measurements"."FK_Trip"="Trips"."TripId") WHERE "Trips"."TaskId"=\'{0}\' ORDER BY "TS_or_Distance" ASC LIMIT {1}'.format(GM_TaskId, load_nrows)
    if all_sensors:
        print('Using all sensors')
        if load_nrows != -1:
            quory = 'SELECT "TS_or_Distance", "T", "lat", "lon", "message" FROM ("Measurements" INNER JOIN "Trips" ON "Measurements"."FK_Trip"="Trips"."TripId") WHERE ("Trips"."TaskId"=\'{0}\' AND "Trips"."Fully_Imported"=\'True\') ORDER BY "TS_or_Distance" ASC LIMIT {1}'.format(
                GM_TaskId, load_nrows)
        else:
            quory = 'SELECT "TS_or_Distance", "T", "lat", "lon", "message" FROM ("Measurements" INNER JOIN "Trips" ON "Measurements"."FK_Trip"="Trips"."TripId") WHERE ("Trips"."TaskId"=\'{0}\' AND "Trips"."Fully_Imported"=\'True\') ORDER BY "TS_or_Distance" ASC'.format(
                GM_TaskId)

    else:
        sensors = ['track.pos', 'acc.xyz', 'obd.spd_veh']
        if add_sensors:
            sensors = sensors + add_sensors
        sensors = str(tuple(sensors))
        print('Loading: ', sensors)
        if load_nrows != -1:
            quory = 'SELECT "TS_or_Distance", "T", "lat", "lon", "message" FROM ("Measurements" INNER JOIN "Trips" ON "Measurements"."FK_Trip"="Trips"."TripId") WHERE ("Trips"."TaskId"=\'{0}\' AND "Trips"."Fully_Imported"=\'True\' AND ("Measurements"."T" IN {1})) ORDER BY "TS_or_Distance" ASC LIMIT {2}'.format(
                GM_TaskId, sensors, load_nrows)
        else:
            quory = 'SELECT "TS_or_Distance", "T", "lat", "lon", "message" FROM ("Measurements" INNER JOIN "Trips" ON "Measurements"."FK_Trip"="Trips"."TripId") WHERE ("Trips"."TaskId"=\'{0}\' AND "Trips"."Fully_Imported"=\'True\' AND ("Measurements"."T" IN {1})) ORDER BY "TS_or_Distance" ASC'.format(
                GM_TaskId, sensors)

    # print(quory)
    print('Fetching from database')
    cursor = conn.cursor()
    meas_data = pd.read_sql(quory, conn, coerce_float=True)
    meas_data.reset_index(inplace=True, drop=True)
    print('Database fetch finished')

    # Extract message
    # =================#
    meas_data['Message'] = meas_data.message.apply(lambda msg: filter_keys(loads(msg)))
    meas_data.drop(columns=['message'], inplace=True, axis=1)
    meas_data.reset_index(inplace=True, drop=True)
    meas_data = meas_data[['TS_or_Distance', 'T', 'lat', 'lon', 'Message']]

    # Extract day and time
    # =================#
    meas_data['Date'] = meas_data.TS_or_Distance.apply(lambda a: pd.to_datetime(a).date())
    meas_data['Time'] = meas_data.TS_or_Distance.apply(lambda a: pd.to_datetime(a).time())
    meas_data.sort_values(by='Time', inplace=True)

    # Get GM trips info #
    # =================#
    print('Loading GM trip information')
    trip_info = get_GM_trips_info(conn_data, ssh_tunnel, task_id=GM_TaskId, prod_db=False, only_GM=True)

    # Close connection
    # ==============#
    if (conn):
        cursor.close()
        conn.close()
        print("PostgreSQL connection is closed")

    # Save files
    # ==============#
    if all_sensors:
        measurements_path = (out_dir + 'GM_db_meas_data_{0}_allsensors.csv').format(GM_TaskId)
    else:
        measurements_path = (out_dir + 'GM_db_meas_data_{0}.csv').format(GM_TaskId)

    measurements_path = measurements_path.replace('//', '/')
    print('Saving files')
    # Save loaded data
    meas_data.to_csv(measurements_path)
    meas_data.to_pickle(measurements_path.replace('.csv', '.pickle'))

    # Save trips info
    trip_info_path = out_dir + 'GM_db_trips_info_{0}.csv'.format(GM_TaskId)

    trip_info.to_csv(trip_info_path)
    trip_info.to_pickle(trip_info_path.replace('.csv', '.pickle'))
    print('Finished saving files')
    return meas_data, trip_info

def get_GM_trips_info(conn_data, ssh_tunnel, prod_db=False, task_id=None, only_GM=False, GM_year=None,
                      GM_min_distance=10):
    # Set up connection
    print("\nConnecting to PostgreSQL database to load the DRD data")

    if prod_db:
        print("\nConnecting to production database")
        db_data = conn_data['prod']
    else:
        print("\nConnecting to development database")
        db_data = conn_data['dev']

    db = db_data['database']
    username = db_data['user']
    password = db_data['password']
    host = db_data['host']
    port = db_data['port']

    # Connection
    conn = psycopg2.connect(database=db, user=username, password=password, host=host,
                            port=port)

    # Quory
    quory = 'SELECT * FROM public."Trips" WHERE "Trips"."Fully_Imported"=\'True\' ORDER BY "TaskId" ASC'

    # Set cursor
    cursor = conn.cursor()

    d = pd.read_sql(quory, conn, coerce_float=True)
    d['Datetime'] = pd.to_datetime(d['StartTimeUtc'])

    # Select GM
    d = d[d['TaskId'] != 0]

    if GM_min_distance:
        d = d[d['DistanceKm'] > GM_min_distance]  # trips with distance>0km

    if GM_year:
        d['Year'] = d['Datetime'].apply(lambda row: row.year)
        d = d[d['Year'] == GM_year]
        d.drop(['Datetime', 'Year'], axis=1, inplace=True)
        d.reset_index(drop=True, inplace=True)

    if task_id:
        d = d[d['TaskId'] == task_id]

    # Close the connection
    cursor.close()
    conn.close()

    return d

def filter_keys(msg):
    remove_list = ['id', 'start_time_utc', 'end_time_utc', 'start_position_display',
                   'end_position_display', 'device', 'duration', 'distanceKm', 'tag',
                   'personal', '@ts', '@uid', '@t', 'obd.whl_trq_est', '@rec']
    msg = {k: v for k, v in msg.items() if k not in remove_list}
    return msg

def extract_string_column(sql_data, col_name='message'):
    # if json
    try:
        sql_data[col_name] = sql_data[col_name].apply(lambda message: loads(message))
    except:
        pass
    keys = sql_data[col_name].iloc[0].keys()
    n_keys = len(keys)
    for i, key in enumerate(keys):
        print('Key {0}/{1}'.format(i, n_keys))
        sql_data[key] = sql_data[col_name].apply(lambda col_data: col_data[key])

    sql_data.drop(columns=[col_name], inplace=True, axis=1)
    return sql_data

def check_nans(sql_data, is_aran=False, exclude_cols=[]):
    n_rows = sql_data.shape[0]
    for col in sql_data.columns:
        if col in exclude_cols:
            continue
        n_nans = sql_data[col].isna().sum()
        n_left = n_rows - n_nans
        print('Number of nans in {0}: {1}/{2}, left: {3}/{2}'.format(col, n_nans, n_rows, n_left))
    return


text:
import importlib
import logging
from multiprocessing import Pool
from os.path import join
import pickle as pkl
import sys

import PIL.Image as Image
import numpy as np
from sacred import Experiment
import torch
import torchvision.transforms as trans
import tqdm

from configuration import CONFIG
from src.MetaSeg.functions.calculate import meta_nn_predict, regression_fit_and_predict
from src.MetaSeg.functions.helper import load_data
from src.MetaSeg.functions.in_out import components_load, get_indices, probs_gt_load
from src.embedding_networks import (
    feature_densenet201,
    feature_resnet18,
    feature_resnet101,
    feature_resnet152,
    feature_vgg16,
    feature_wide_resnet101,
)
from src.log_utils import log_config

ex = Experiment("compute_embeddings")

log = logging.getLogger()
log.handlers = []

log_format = logging.Formatter(
    "%(asctime)s || %(name)s - [%(levelname)s] - %(message)s"
)

streamhandler = logging.StreamHandler(sys.stdout)
streamhandler.setFormatter(log_format)
log.addHandler(streamhandler)

log.setLevel("INFO")
ex.logger = log

# this mean and stardard deviation have been used for all PyTorch models during
# training. Use them during prediction of feature embeddings
imagenet_mean = (0.485, 0.456, 0.406)
imagenet_std = (0.229, 0.224, 0.225)

def wrapper_cutout_components(args):
    """Wrapper for the multiprocessing pool."""
    return cutout_components(*args)

# noinspection PyArgumentList
def cutout_components(
    component_indices,
    image_index,
    iou_pred,
    dataset="a2d2",
    min_height=64,
    min_width=64,
    min_crop_height=128,
    min_crop_width=128,
    model_name="deeplabv3plus",
):
    """Cuts out all components of the image if they match the minimum size requirements.

    Args:
        component_indices (sequence): Sequence of local component numbers.
        image_index (int): Index of the image to process.
        iou_pred (numpy array): Array of iou predictions for each component
        dataset (str): Name of the dataset to process.
        min_height (int): Minimum height of the component to be processed. Useful if
            you want to pass the crop to a neural network.
        min_width (int): Minimum height of the component to be processed. Useful if you
            want to pass the crop to a neural network .
        min_crop_width (int): Minimum width the resulting bounding box should have.
            If the segment satisfies the min_width but is smaller then min_crop_width
            the bounding box is getting enlarged until the min_crop_width is satisfied.
        min_crop_height: Minimum height the resulting bounding box should have. If the
            segment satisfies the min_height but is smaller then min_crop_height the
            bounding box is getting enlarged until the min_crop_height is satisfied.
        model_name (str): Name of the model used.

    Returns: Dictionary with
        'dataset': Name of the dataset the image belongs to.
        'model_name': Name of the model used for the prediction
        'data': List of raw image crops containing the matching components
        'addresses':
            List of addresses where to find the crop (path to the image file
            and corner coordinates of the box (top, left, bottom, right)
    """
    components = components_load(
        image_index,
        components_dir=join(CONFIG.metaseg_io_path, "components", model_name, dataset),
    )
    crops = {
        "dataset": dataset,
        "model_name": model_name,
        "embeddings": [],
        "boxes": [],
        "image_index": image_index,
        "iou_pred": iou_pred,
        "component_indices": [],
        "segment_indices": [],
        "img_crops": [],
    }
    for cindex in component_indices:
        segment_indices = np.argwhere(components == cindex)
        if segment_indices.shape[0] > 0:
            upper, left = segment_indices.min(0)
            lower, right = segment_indices.max(0)
            if (lower - upper) < min_height or (right - left) < min_width:
                continue

            if (right - left) < min_crop_width:
                margin = min_crop_width - (right - left)
                if left - (margin // 2) < 0:
                    left = 0
                    right = left + min_crop_width
                elif right + (margin // 2) > components.shape[1]:
                    right = components.shape[1]
                    left = right - min_crop_width

                if right > components.shape[1] or left < 0:
                    raise IndexError(
                        "Image with shape {} is too small for a {} x {} crop".format(
                            components.shape, min_crop_height, min_crop_width
                        )
                    )
            if (lower - upper) < min_crop_height:
                margin = min_crop_height - (lower - upper)
                if upper - (margin // 2) < 0:
                    upper = 0
                    lower = upper + min_crop_height
                elif lower + (margin // 2) > components.shape[0]:
                    lower = components.shape[0]
                    upper = lower - min_crop_height

                if lower > components.shape[0] or upper < 0:
                    raise IndexError(
                        "Image with shape {} is too small for a {} x {} crop".format(
                            components.shape, min_crop_height, min_crop_width
                        )
                    )

            crops["boxes"].append((left, upper, right, lower))
            crops["component_indices"].append(cindex)
            crops["segment_indices"].append(segment_indices)
    return crops

def get_image_index_to_components(component_indices, start):
    """Maps global component indices and start values to their local component indices
    and image index.

    Args:
        component_indices (sequence): Sequence of component indices.
        start (sequence): Sequence of indices where components of each image start
    """
    out = {}

    for i in range(len(start) - 1):
        index = component_indices[
            np.logical_and(
                start[i] <= component_indices, component_indices < start[i + 1]
            )
        ]
        out[i] = [j - start[i] + 1 for j in index]
    return out

@ex.capture
def get_embedding(image, net, args):
    """Computes the output of the supplied neural network with respect to the supplied
    image.

    Args:
        image (tensor): Image tensor to be processed by the neural network.
        net (nn.Module): Neural Network to use.
        args: Arguments provided by sacred.

    Returns: Output tensor of the neural network moved to the cpu

    """
    image = image.cuda(args["gpu"])
    with torch.no_grad():
        out = net(image)
    return out.data.cpu().squeeze().numpy()

def get_component_gt(gt, segment_indices):
    """Computes the ground truth for the supplied gt labels and segment indices."""
    cls, cls_counts = np.unique(
        gt[segment_indices[:, 0], segment_indices[:, 1]], return_counts=True
    )
    # cls, cls_counts = np.unique(gt[box[1]:box[3], box[0]:box[2]], return_counts=True)
    return cls[np.argsort(cls_counts)[-1]]

def get_component_pred(pred, segment_indices):
    """Computes the prediction of a segment based on the supplied predictions and
    segment indices."""
    return pred[segment_indices[0, 0], segment_indices[0, 1]]

@ex.config
def config():
    args = dict(
        net="densenet201",  # Network architecture used for computing visual features
        datasets=(CONFIG.TRAIN_DATASET.name, CONFIG.DATASET.name),
        # First specified dataset will always be used as source domain
        load_file=None,  # File in which segments got already extracted. If specified
        # the file get's loaded and
        # the embeddings in there are overwritten.
        gpu=CONFIG.GPU_ID,  # GPU id to use for computation of features for the
        # embedding space
        n_jobs=CONFIG.NUM_CORES,  # Number of processes to use for the extraction of
        # all bounding boxes
        min_height=128,  # Minimum height of a predicted segment
        min_width=128,  # Minimum width of a predicted segment
        min_crop_height=128,  # Minimum height of the resulting bounding box, can be
        # larger than min_height
        min_crop_width=128,  # Minimum width of the resulting bounding box, can be
        # larger than min_width
        meta_nn_path="./src/meta_nn.pth",  # Path to the meta segmentation model
        iou_threshold=0.5,  # Threshold to use for extracting segments based on
        # predicted IoU
        meta_model=CONFIG.META_MODEL_TYPE,  # Model type to use for meta segmentation
    )

    if args["meta_model"] == "neural":
        args["meta_nn_path"] = "./src/meta_nn.pth"

    args["save_file"] = join(
        CONFIG.metaseg_io_path,
        "embeddings_{}_{}_{}.p".format(
            args["min_height"], args["min_width"], args["net"]
        ),
    )

@ex.automain
def main(args, _run, _log):
    log_config(_run, _log)
    # load a network architecture
    _log.info("Loading {}...".format(args["net"]))
    if args["net"] == "vgg16":
        net = feature_vgg16()
    elif args["net"] == "resnet18":
        net = feature_resnet18()
    elif args["net"] == "resnet101":
        net = feature_resnet101()
    elif args["net"] == "resnet152":
        net = feature_resnet152()
    elif args["net"] == "wide_resnet101":
        net = feature_wide_resnet101()
    elif args["net"] == "densenet201":
        net = feature_densenet201()
    else:
        raise ValueError
    net = net.cuda(args["gpu"])
    net.eval()

    # if no precomputed segments have been supplied, they have to be computed
    if args["load_file"] is None:
        _log.info("Loading Metrics...")
        xa_all = []
        start_others = []
        pred_test = []
        dataset_assignments = []
        image_indices = []

        # the first dataset of the 'datasets' configuration serves as source domain
        # dataset. Metric statistics of this dataset are used to normalize the target
        # domain metric statistics. This is why it has to get loaded too.
        if args["meta_model"] == "neural" and all(
            i in torch.load(args["meta_nn_path"]).keys()
            for i in [
                "train_xa_mean",
                "train_xa_std",
                "train_classes_mean",
                "train_classes_std",
            ]
        ):
            _log.info(
                "Loading values for normalization from saved model file '{}'".format(
                    args["meta_nn_path"]
                )
            )
            model_dict = torch.load(args["meta_nn_path"])
            xa_mean = model_dict["train_xa_mean"]
            xa_std = model_dict["train_xa_std"]
            classes_mean = model_dict["train_classes_mean"]
            classes_std = model_dict["train_classes_std"]
        else:
            _log.info("{}...".format(args["datasets"][0]))
            (
                xa,
                ya,
                x_names,
                class_names,
                xa_mean,
                xa_std,
                classes_mean,
                classes_std,
                *_,
                start,
                pred,
            ) = load_data(args["datasets"][0])

        # Now load all other metric statistics and normalize them using the source
        # domain mean and standard deviation
        for i, d in enumerate(args["datasets"][1:], start=1):
            _log.info("{} ...".format(d))
            num_imgs = get_indices(
                join(CONFIG.metaseg_io_path, "metrics", "deeplabv3plus", d)
            )
            xa_tmp, *_, start_tmp, pred_tmp = load_data(
                d,
                num_imgs=num_imgs,
                xa_mean=xa_mean,
                xa_std=xa_std,
                classes_mean=classes_mean,
                classes_std=classes_std,
            )
            xa_all.append(xa_tmp)
            pred_test.append(pred_tmp)
            dataset_assignments += [i] * len(num_imgs)
            image_indices += num_imgs
            start_others.append(start_tmp)

        # combine them into single arrays
        xa_all = np.concatenate(xa_all).squeeze()
        pred_test = np.concatenate(pred_test).squeeze()
        dataset_assignments = np.array(dataset_assignments).squeeze()
        image_indices = np.array(image_indices).squeeze()

        for starts in start_others[1:]:
            start_others[0] += [s + start_others[0][-1] for s in starts[1:]]
        start_all = start_others[0]
        del xa_tmp, start_tmp, pred_tmp, start_others

        _log.debug("Shape of metrics array: {}".format(xa_all.shape))

        # Using the normalized metric statistics use a meta segmentation network
        # pretrained on the source domain to predict IoU
        _log.info("Predicting IoU...")
        if args["meta_model"] == "neural":
            ya_pred_test = meta_nn_predict(
                pretrained_model_path=args["meta_nn_path"],
                x_test=xa_all,
                gpu=args["gpu"],
            )
        elif args["meta_model"] == "linear":
            ya_pred_test, _ = regression_fit_and_predict(
                x_train=xa, y_train=ya, x_test=xa_all
            )
        else:
            raise ValueError("Meta model {} not supported.".format(args["meta_model"]))

        # Now the different filters are getting applied to the segments
        _log.info("Filtering segments...")
        inds = np.zeros(pred_test.shape[0]).astype(np.bool)

        # Filter for the predicted IoU to be less than the supplied threshold
        inds = np.logical_or(inds, (ya_pred_test < args["iou_threshold"]))

        # Filter for extracting segments with predefined class predictions
        if hasattr(
            importlib.import_module(CONFIG.TRAIN_DATASET.module_name),
            "pred_class_selection",
        ):
            pred_class_selection = getattr(
                importlib.import_module(CONFIG.TRAIN_DATASET.module_name),
                "pred_class_selection",
            )
            inds = np.logical_and(inds, np.isin(pred_test, pred_class_selection))

        _log.info("Filtered components (not checked for minimum size):")
        train_dat = getattr(
            importlib.import_module(CONFIG.TRAIN_DATASET.module_name),
            CONFIG.TRAIN_DATASET.class_name,
        )(**CONFIG.TRAIN_DATASET.kwargs)
        _log.info(
            "\t{:^{width}s} | Filtered | Total".format(
                "Class name",
                width=max(
                    [len(v[0]) for v in train_dat.pred_mapping.values()]
                    + [len("Class name")]
                ),
            )
        )
        for cl in np.unique(pred_test).flatten():
            _log.info(
                "\t{:^{width}s} | {:>8d} | {:<8d}".format(
                    train_dat.pred_mapping[cl][0],
                    inds[pred_test == cl].sum(),
                    (pred_test == cl).sum(),
                    width=max(
                        [len(v[0]) for v in train_dat.pred_mapping.values()]
                        + [len("Class name")]
                    ),
                )
            )

        # Aggregating arguments for extraction of component information.
        inds = np.argwhere(inds).flatten()
        component_image_mapping = get_image_index_to_components(inds, start_all)
        p_args = [
            (
                v,
                image_indices[k],
                ya_pred_test[start_all[k] : start_all[k + 1]],
                args["datasets"][dataset_assignments[k]],
                args["min_height"],
                args["min_width"],
                args["min_crop_height"],
                args["min_crop_width"],
                "deeplabv3plus",
            )
            for k, v in component_image_mapping.items()
        ]

        # Extracting component information can be parallelized in a multiprocessing pool
        _log.info("Extracting component information...")
        with Pool(args["n_jobs"]) as p:
            r = list(
                tqdm.tqdm(p.imap(wrapper_cutout_components, p_args), total=len(p_args))
            )
        r = [c for c in r if len(c["component_indices"]) > 0]

        _log.info("Computing embeddings...")
        crops = {
            "embeddings": [],
            "image_path": [],
            "image_index": [],
            "component_index": [],
            "box": [],
            "gt": [],
            "pred": [],
            "dataset": [],
            "model_name": [],
            "image_level_index": [],
            "iou_pred": [],
        }
        # process all extracted crops and compute feature embeddings
        for c in tqdm.tqdm(r):
            # load image
            preds, gt, image_path = probs_gt_load(
                c["image_index"],
                input_dir=join(
                    CONFIG.metaseg_io_path, "input", c["model_name"], c["dataset"]
                ),
                preds=True,
            )

            crops["image_path"].append(image_path)
            crops["model_name"].append(c["model_name"])
            crops["dataset"].append(c["dataset"])
            crops["image_index"].append(c["image_index"])
            crops["iou_pred"].append(c["iou_pred"])

            image = Image.open(image_path).convert("RGB")
            for i, b in enumerate(c["boxes"]):
                img = trans.ToTensor()(image.crop(b))
                img = trans.Normalize(mean=imagenet_mean, std=imagenet_std)(img)
                crops["embeddings"].append(get_embedding(img.unsqueeze(0), net))
                crops["box"].append(b)
                crops["component_index"].append(c["component_indices"][i])
                crops["image_level_index"].append(len(crops["image_path"]) - 1)
                crops["gt"].append(get_component_gt(gt, c["segment_indices"][i]))
                crops["pred"].append(get_component_pred(preds, c["segment_indices"][i]))

        _log.info("Saving data...")
        with open(args["save_file"], "wb") as f:
            pkl.dump(crops, f)
    else:
        with open(args["load_file"], "rb") as f:
            crops = pkl.load(f)

        _log.info("Computing embeddings...")
        boxes = np.array(crops["box"]).squeeze()
        image_level_index = np.array(crops["image_level_index"]).squeeze()
        crops["embeddings"] = []
        for i, image_path in tqdm.tqdm(
            enumerate(crops["image_path"]), total=len(crops["image_path"])
        ):
            image = Image.open(image_path).convert("RGB")
            for j in np.argwhere(image_level_index == i).flatten():
                img = trans.ToTensor()(image.crop(boxes[j]))
                img = trans.Normalize(mean=imagenet_mean, std=imagenet_std)(img)
                crops["embeddings"].append(get_embedding(img.unsqueeze(0), net))

        if "plot_embeddings" in crops:
            del crops["plot_embeddings"]
        if "nn_embeddings" in crops:
            del crops["nn_embeddings"]

        _log.info("Saving data...")
        with open(args["save_file"], "wb") as f:
            pkl.dump(crops, f)


text:
# Licensed under a 3-clause BSD style license - see LICENSE.rst

# This sub-module is destined for common non-package specific utility
# functions that will ultimately be merged into `astropy.utils`

from astropy.utils.compat import override__dir__

try:
    from astropy.utils.introspection import find_mod_objs
except ImportError:
    from astropy.utils.misc import find_mod_objs

max_stars_repo_name: alexrudy/astropyephem

max_issues_repo_name: alexrudy/astropyephem

max_forks_repo_name: alexrudy/astropyephem

reason: from astropy


text:
"""
 post-processing solution from rinex data
"""
import numpy as np
from copy import copy, deepcopy
from rtkpos import rtkpos, rtkinit
import __ppk_config as cfg
import rinex as rn
from pntpos import pntpos
import rtkcmn as gn

def combres(solf, solb):
    # combine forward/backward solutions
    pri = [7,1,2,3,4,5,1,6] # priority of solution status
    i, j, solc = 0, len(solb) - 1, []
    gn.trace(3, 'combres: # forward = %d, # backward = %d\n' % (len(solf),
        len(solb)))
    while i < len(solf) or j >= 0:
        if i >= len(solf):
            sol = deepcopy(solb[j])
        elif j < 0:
            sol = deepcopy(solf[i])
        elif not (solf[i].stat == gn.SOLQ_NONE and solb[j].stat == gn.SOLQ_NONE):
            tt = gn.timediff(solf[i].t, solb[j].t)
            if tt < -gn.DTTOL:
                sol = deepcopy(solf[i])
                j += 1
            elif tt > gn.DTTOL:
                sol = deepcopy(solb[j])
                i -= 1
            elif pri[solf[i].stat] < pri[solb[j].stat]:
                sol = deepcopy(solf[i])
            elif pri[solf[i].stat] > pri[solb[j].stat]:
                sol = deepcopy(solb[j])
            else:
                sol = deepcopy(solf[i])
                sol.t = gn.timeadd(sol.t, -tt / 2)
                sol.rr[0:3], sol.qr[0:3,0:3] = gn.smoother(solf[i].rr[0:3],
                    solb[j].rr[0:3], solf[i].qr, solb[j].qr)
            solc.append(sol)
            gn.trace(4, '  %d: f=%d %d b=%d %d tt=%.3f\n' % (sol.t.time,
                solf[i].t.time, solf[i].stat, solb[j].t.time, solb[j].stat, tt))
        i, j = i + 1, j - 1
    return solc

def firstpos(nav, rov, base, dir):
    # find rover position from first obs,
    obsr, obsb = rn.first_obs(nav, rov, base, dir)
    sol = pntpos(obsr, nav)
    # repeat until get solution
    while sol.stat == gn.SOLQ_NONE:
        obsr, obsb = rn.next_obs(nav, rov, base, dir)
        sol = pntpos(obsr, nav)
    gn.trace(3, 'init rr: %.2f %.2f %.2f: %d\n' % (sol.rr[0], sol.rr[1],
            sol.rr[2], sol.stat))
    nav.x[0:6] = copy(sol.rr[0:6])
    nav.rr[0:3] = copy(sol.rr[0:3])

def sqrtvar(cov):
    " sqrt of covariance "
    return np.sqrt(abs(cov)) * np.sign(cov)

def savesol(sol, solfile):
    D2R = gn.rCST.D2R
    solhdr = '%  GPST          latitude(deg) longitude(deg)  height(m)   Q  ' \
        'ns   sdn(m)   sde(m)   sdu(m)  sdne(m)  sdeu(m)  sdun(m) age(s)  ratio\n'
    with open(solfile, 'w') as outfile:
        outfile.write(solhdr)
        for s in sol:
                if s.stat == gn.SOLQ_NONE:
                    continue
                wk, sec = gn.time2gpst(s.t)
                llh = gn.ecef2pos(s.rr[0:3])
                std = sqrtvar(gn.covenu(llh, s.qr))
                fmt = '%4d %10.3f %14.9f %14.9f %10.4f %3d %3d %8.4f' + \
                    '  %8.4f %8.4f %8.4f %8.4f %8.4f %6.2f %6.1f\n'
                outfile.write(fmt % (wk, sec, llh[0]/D2R, llh[1]/D2R, llh[2],
                    s.stat, s.ns, std[1,1], std[0,0], std[2,2], std[0,1],
                    std[2,0], std[1,2], s.age, s.ratio))

def procpos(nav, rov, base):

    try:
        if nav.filtertype != 'backward':
            # run forward solution
            firstpos(nav, rov, base, dir=1)
            rtkpos(nav, rov, base, dir=1)
            sol0 = deepcopy(nav.sol)
            savesol(sol0,'forward.pos')
        if nav.filtertype != 'forward':
            # run backward solution
            if nav.filtertype != 'combined_noreset':
                # reset filter states
                rb = nav.rb.copy()
                eph, geph = nav.eph.copy(), nav.geph.copy()
                glofrq = nav.glofrq.copy()
                maxepoch = nav.maxepoch
                nav = rtkinit(cfg)
                nav.rb = rb
                nav.eph, nav.geph = eph, geph
                nav.glofrq = glofrq
                nav.maxepoch = maxepoch
                firstpos(nav, rov, base, dir=-1)
            else: # combined_noreset
                nav.sol = [nav.sol[-1]]
            rtkpos(nav, rov, base, dir=-1)
            savesol(nav.sol,'backward.pos')
        if nav.filtertype == 'combined' or nav.filtertype == 'combined_noreset':
            sol = combres(sol0, nav.sol)
            savesol(sol,'combined.pos')
            return sol
    except KeyboardInterrupt:
        pass
    return nav.sol

max_stars_repo_name: rtklibexplorer/rtklib-py

max_issues_repo_name: rtklibexplorer/rtklib-py

max_forks_repo_name: rtklibexplorer/rtklib-py


text:
"""Deep sea treasure envirnment

mostly compatible with OpenAI gym envs
"""

from __future__ import print_function

import sys
import math
import random
import itertools

import numpy as np
import scipy.stats

from utils import truncated_mean, compute_angle, pareto_filter

SEA_MAP = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [18, 26, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [-1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [-1, -1, -1, 44, 48.2, 0, 0, 0, 0, 0, 0, 0],
    [-1, -1, -1, -1, -1, 56, 0, 0, 0, 0, 0, 0],
    [-1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0],
    [-1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0],
    [-1, -1, -1, -1, -1, -1, 72, 76.3, 0, 0, 0, 0],
    [-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0],
    [-1, -1, -1, -1, -1, -1, -1, -1, 90, 0, 0, 0],
    [-1, -1, -1, -1, -1, -1, -1, -1, -1, 100, 0, 0]]

HOME_POS = (0, 0)

ACT_LEFT = 0
ACT_RIGHT = 1
ACT_UP = 2
ACT_DOWN = 3

ACTIONS = ["Left", "Right", "Up", "Down"]
ACTION_COUNT = len(ACTIONS)

class DeepSeaTreasure():
    """Deep sea treasure environment
    """

    def __init__(self, sea_map=SEA_MAP, full=False, view=(5,5), scale=1):
        assert view[0] % 2 == 1
        assert view[1] % 2 == 1
        self.fully_observable=full
        self.map_height = len(sea_map)
        self.map_width = len(sea_map[0])
        self.view_height = view[0]
        self.view_width = view[1]
        self.scale = scale
        self.unit = 255

        self.observe_height = self.map_height if full else view[0]
        self.observe_width = self.map_width if full else view[1]

        self.observation_space = np.zeros((self.observe_width*scale, self.observe_height*scale, 3))
        self.nb_count = ACTION_COUNT
        self.action_space = np.arange(ACTION_COUNT)

        self.action_rand = False

        self.submarine_pos = list(HOME_POS)
        self.sea_map = sea_map
        self._static_map = self._create_map(sea_map)
        self.game_map = self.get_blank_map()

        self.end = False
        self.obj_cnt = 2

        self._margined_width = self.map_width + self.view_width - 1
        self._margined_height = self.map_height + self.view_height - 1

        self._w_min = int(self.view_width/2)
        self._w_max = int(self.view_width/2 + self.map_width)
        self._h_min = int(self.view_height/2)
        self._h_max = int(self.view_height/2 + self.map_height)

    def _create_map(self, sea_map):
        game_map = np.zeros((self.map_height, self.map_width, 3))
        for row in range(self.map_height):
            for col in range(self.map_width):
                if sea_map[row][col] == -1:
                    game_map[row][col][0] = self.unit # seafloor
                elif sea_map[row][col] != 0:
                    game_map[row][col][1] = self.unit # treasure
                else:
                    game_map[row][col][2] = self.unit # water
        return game_map

    def get_blank_map(self):
        return np.copy(self._static_map)

    def step(self, action, frame_skip=1, incremental_frame_skip=True):
        """Perform the given action `frame_skip` times
         ["Left", "Right", "Up", "Down"]
        Arguments:
            action {int} -- Action to perform, ACT_MINE (0), ACT_LEFT (1), ACT_RIGHT (2), ACT_ACCEL (3), ACT_BRAKE (4) or ACT_NONE (5)

        Keyword Arguments:
            frame_skip {int} -- Repeat the action this many times (default: {1})
            incremental_frame_skip {bool} -- If True, frame_skip actions are performed in succession, otherwise the repeated actions are performed simultaneously (e.g., 4 accelerations are performed and then the cart moves).

        Returns:
            tuple -- (observation, reward, terminal, info) tuple
        """

        reward = np.zeros(self.obj_cnt)
        reward[-1] = -1

        if self.action_rand:
            prob = np.array([.05]*self.nb_count)
            prob[action] += 0.8
            action = np.random.choice(self.action_space, p=prob)

        move = (0, 0)
        if action == ACT_LEFT:
            move = (0, -1)
        elif action == ACT_RIGHT:
            move = (0, 1)
        elif action == ACT_UP:
            move = (-1, 0)
        elif action == ACT_DOWN:
            move = (1, 0)

        changed = self.move_submarine(move)
        reward[0] = self.sea_map[self.submarine_pos[0]][self.submarine_pos[1]]

        if changed:
            self.render()

        info, observation = self.get_state(True)
        # observation (pixels), reward (list), done (boolean), info (dict)
        return observation, reward, self.end, info

    def move_submarine(self, move):
        target_y = self.submarine_pos[0] + move[0]
        target_x = self.submarine_pos[1] + move[1]

        if 0 <= target_x < self.map_width and 0 <= target_y < self.map_height:
            if self.game_map[target_y][target_x][0] != self.unit:
                self.submarine_pos[0] = target_y
                self.submarine_pos[1] = target_x

            if self.game_map[target_y][target_x][1] == self.unit:
                self.end = True
            return True
        return False

    def get_state(self, update=True):
        """Returns the environment's full state, including the cart's position,
        its speed, its orientation and its content, as well as the environment's
        pixels

        Keyword Arguments:
            update {bool} -- Whether to update the representation (default: {True})

        Returns:
            dict -- dict containing the aforementioned elements
        """

        info = {
            "position": self.submarine_pos,
            "pixels": self.game_map
        }

        observation = self.get_observation()

        return info, observation

    def get_observation(self):
        """Create a partially observable observation with the given state.
        Half size of state["pixels"] with origin of state["position"], and the
        overflow part is black

        Returns:
            array: 3d array as the same type of state["pixels"]
        """

        if self.fully_observable:
            self.observation_space = np.copy(self.game_map)
            return self.scale_map(self.game_map)

        margined_map = np.zeros((self._margined_height, self._margined_width, 3), dtype=np.uint8)
        margined_map[self._w_min : self._w_max, self._h_min : self._h_max, :] = self.game_map

        min_y = self.submarine_pos[0]
        min_x = self.submarine_pos[1]

        observe = margined_map[min_y : int(min_y + self.observe_height), min_x : int(min_x + self.observe_width), :]

        self.observation_space = self.scale_map(observe)
        return self.observation_space

    def reset(self):
        """Resets the environment to the start state

        Returns:
            [type] -- [description]
        """

        self.end = False
        self.submarine_pos = list(HOME_POS)
        self.render()
        _, observation = self.get_state()
        return observation

    def __str__(self):
        string = "Completed: {} ".format(self.end)
        string += "Position: {} ".format(self.submarine_pos)
        return string

    def render(self):
        """Update the environment's representation
        """

        self.game_map = self.get_blank_map()
        self.game_map[self.submarine_pos[0]][self.submarine_pos[1]] = self.unit

    def scale_map(self, frame):
        return frame.repeat(self.scale, axis=0).repeat(self.scale, axis=1)

    def show(self, frame=None, plot=False):
        frame = frame or self.observation_space

        if not plot:
            for i in range(frame.shape[0]):
                print(frame[i,:,0], frame[i,:,1], frame[i,:,2])
        else:
            import matplotlib.pyplot as plt
            image = frame
            fig = plt.imshow(image)
            plt.show()

if __name__ == '__main__':

    env = DeepSeaTreasure(view=(5,5), full=False, scale=1)
    print(env.nb_count)
    print(env.observation_space.shape)
    o_t = env.reset()
    terminal = False

    env.show(plot=True)

    while not terminal:
        a_t = int(input("0:left, 1:right, 2:up, 3:down | choose: "))
        o_t1, r_t, terminal, s_t1 = env.step(a_t)
        env.show(plot=True)

        o_t = o_t1
        print("Taking action", a_t, "at", s_t1["position"], "with reward", r_t)
    env.reset()

reason: import numpy,import scipy


text:
from collections import namedtuple
from itertools import product

import gurobipy as gp
import numpy as np
import pandas as pd
import xpress as xp

np.set_printoptions(edgeitems=30, linewidth=1000, precision=6, suppress=False)
np.set_printoptions(formatter={'float':lambda x: f"{x:.6f}"})
pd.set_option("precision", 6)

class EquilibriumModel:
    def __init__(self, params, flags=None):
        self.model = xp.problem()
        self.params = params
        self.flags = flags or {}
        self.vars = {}

        # Unpack parameters
        self.__dict__.update(params.__dict__)

        # Set parameter controlling 'Market power adjustment'
        self.Y = 1 if self.flags.get("MARKET_TYPE") == "C" else 0

        # Inferred sets
        self.S = range(self.n_suppliers)
        self.N = range(self.n_nodes)
        self.SN = list(product(self.S, self.N))

    def add_variables(self):
        self.vars = {
            "Q_P": np.array([xp.var() for _ in self.S]),
            "Q_C": np.array([xp.var() for _ in self.SN]).reshape(self.n_suppliers, self.n_nodes)
        }
        self.__dict__.update(self.vars)
        self.model.addVariable(*self.vars.values())

    def set_objective(self):
        # Subexpressions
        self.Q_n = self.Q_C.sum(axis=0)                                 # Consumed quantity per node
        self.p_n = self.a - self.b * self.Q_n                           # Price per node
        self.f_n = self.c * self.Q_P + self.d * self.Q_P**2             # Production cost per supplier

        self.TC = xp.Sum(self.f_n + (self.c_f * self.Q_C).sum(axis=1))  # Total costs
        self.MPA = xp.Sum(0.5 * self.b * (self.Q_C**2).sum(axis=0))     # Market power adjustment
        self.CS = xp.Sum(0.5 * self.b * self.Q_n**2)                    # Consumer surplus
        self.REV = xp.Sum(self.p_n * self.Q_n)                          # Revenue

        # Objective function
        obj = self.TC - self.CS - self.REV + self.Y * self.MPA
        self.model.setObjective(obj, sense=xp.minimize)

    def add_constraints(self):
        self.constraints = {
            # Transport capacity per arc
            "capacity_con": [self.Q_C[i,n] <= self.cap_f[i,n] for (i, n) in self.SN],

            # Supply must equal demand
            "supply_demand_con": [self.Q_P[i] == xp.Sum(self.Q_C[i,n] for n in self.N) for i in self.S]
        }
        self.__dict__.update(self.constraints)
        self.model.addConstraint(*self.constraints.values())

    def build_model(self):
        self.add_variables()
        self.set_objective()
        self.add_constraints()
        return self

    def solve(self):
        # Solve model in Gurobi
        self.model.write("./model", "lp")
        self.gurobi_model = gp.read("./model.lp")
        self.gurobi_model.setParam('OutputFlag', 0)
        self.gurobi_model.optimize()

        # Extract solution
        self.sol = self.get_solution()
        self.duals = self.get_duals()

        # Results
        if self.flags.get('PRINT_SOLUTION'):
            self.print_solution(self.sol)
        if self.flags.get('PRINT_VARIABLES'):
            self.print_variables(self.sol)

    def get_solution(self):
        """ Reads of the solution from the solved problem instance."""
        sizes = [v.size for v in self.vars.values()]
        shapes = [v.shape for v in self.vars.values()]
        flat_sols = [v.X for v in self.gurobi_model.getVars()]
        sols = np.split(flat_sols, np.array(sizes).cumsum()[:-1])
        sols = [sol.reshape(shape) for sol, shape in zip(sols, shapes)]
        dict_ = dict(zip(self.vars, sols))
        return namedtuple('Solution', dict_)(**dict_)

    def get_duals(self):
        """ Reads of the dual values from the solved problem instance."""
        sizes = [len(c) for c in self.constraints.values()]
        flat_duals = [c.Pi for c in self.gurobi_model.getConstrs()]
        duals = np.split(flat_duals, np.array(sizes).cumsum()[:-1])
        dict_ = dict(zip(self.constraints, duals))
        return namedtuple('Duals', dict_)(**dict_)

    def print_variables(self, sol):
        for k, v in sol._asdict().items():
            print("\n")
            print(f"{'Solution for ' + k:^30}")
            print("="*30)
            print(v)

    def print_solution(self, sol):
        network_str = f"NETWORK_TYPE={self.flags.get('NETWORK_TYPE')}"
        market_str = f"MARKET_TYPE={self.flags.get('MARKET_TYPE')}"
        print(f"\n\n{'='*10} SOLUTION FOR [{network_str}, {market_str}] {'='*10}")
        print(f"\nOBJECTIVE: {self.gurobi_model.ObjVal}")

        # Subexpressions
        Q_n = sol.Q_C.sum(axis=0)                               # Consumed quantity per node
        p_n = self.a - self.b * Q_n                             # Price per node
        f_n = self.c * sol.Q_P + self.d * sol.Q_P**2            # Production cost per supplier

        TC = np.sum(f_n + (self.c_f * sol.Q_C).sum(axis=1))     # Total costs
        MPA = np.sum(0.5 * self.b * (sol.Q_C**2).sum(axis=0))   # Market power adjustment
        CS = np.sum(0.5 * self.b * Q_n**2)                      # Consumer surplus
        REV = np.sum(p_n * Q_n)                                 # Revenue

        print(f"TC:  {TC}")
        print(f"MPA: {MPA}")
        print(f"CS:  {CS}")
        print(f"REV: {REV}")

        # Answers to subtask (c)
        production = sol.Q_P
        consumption = sol.Q_C.sum(axis=0)
        price = self.a - self.b * consumption

        print(f"Production:  {production}")
        print(f"Consumption: {consumption}")
        print(f"Price:       {price}")
        print(f"\nTotal supplier profits (REV - TC): {REV - TC}")
        print(f"Total consumer surplus (CS):       {CS}")

        # Answers to subtask (e)
        indices = [(i+1, n+1) for i, n in self.SN]
        rows = [
            {
                "MR": self.a[n] - self.b[n] * consumption[n] - self.Y * self.b[n] * sol.Q_C[i, n],
                "MC": self.c[i] + 2 * self.d[i] * sol.Q_C[i,:].sum() + self.c_f[i,n],
                "Dual": self.duals.capacity_con[count]
            } for count, (i, n) in enumerate(self.SN)
        ]
        print("\n", pd.DataFrame(data=rows, index=indices), "\n", sep='')


text:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Dense

dataset = pd.read_csv('irisSLP.csv')
dataset = pd.DataFrame(dataset)
print (dataset.columns)
dataset = dataset.values

dataset = np.array(dataset)

X = dataset[:, :4]
types = dataset[:, -1]

y = []

for i in range(len(types)):
    if types[i] == 'Iris-setosa':
        y.append([1, 0])
    elif types[i] == 'Iris-virginica':
        y.append([0, 1])

y = np.array(y)

print (X.shape, y.shape)

model = Sequential()
model.add(Dense(2, input_shape=[4, ], activation='sigmoid'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mse', 'accuracy'])
model.summary()

hist = model.fit(X, y, epochs=100)
print (hist.__dict__)
losses = (hist.__dict__['history']['loss'])
accs = (hist.__dict__['history']['acc'])
epochs = np.arange(100)

plt.plot(epochs, losses, color='#5f27cd')
plt.plot(epochs, accs, color='#5f27cd')
plt.show()


text:
"""The heart of the *oyb* package. Contains orbital models and conversions.
"""

import datetime
import numpy
from math import pi, cos, sin, acos, asin
from oyb import anomaly, rot, earth

class Orbit(object):
    """Restricted two-body propagation model
    """

    def __init__(self, a_m=None, e=None, i_rad=None, O_rad=None, w_rad=None, M_rad=None, tEpoch_dt=None):
        """Initializes a restricted two-body propagation model for a spherical
           earth. Defaults to a circular GEO orbit with all angles set to 0.
           (Epoch is set to the UTC time when the object is created.)
        """
        self.tEpoch_dt = tEpoch_dt if tEpoch_dt is not None else datetime.datetime.utcnow()
        self.a_m = a_m if a_m is not None else ((earth.tSidDay_s / (2 * pi))**2 * earth.mu_m3ps2)**(1/3)
        self.e = e
        self.i_rad = i_rad
        self.O_rad = O_rad
        self.w_rad = w_rad
        self.M_rad = M_rad

    def __str__(self):
        """Converts an Orbit object into a string representation (invoked by the
           *str* and *print* functions) that references the shape (altitude at
           perigee and apogee) and object location in memory.
        """
        hPer_m, hApo_m = self.getShape()
        return '<%g x %g [km] %s at 0x%08x>' % (hPer_m * 1e-3, hApo_m * 1e-3, self.__class__.__name__, id(self))

    def getPeriod(self):
        """Returns the period of the current orbit, in seconds.
        """
        T_s = 2 * pi * (self.a_m**3 / earth.mu_m3ps2)**0.5
        return T_s

    def getTrue(self, t_dt=None):
        """Returns the true anomaly of the object when propagated to a given
           datetime.
        """
        if t_dt is None:
            t_dt = self.tEpoch_dt
        dt_s = (t_dt - self.tEpoch_dt).total_seconds()
        dM_rad = dt_s * 2 * pi / self.getPeriod()
        M_rad = (self.M_rad + dM_rad) % (2 * pi)
        return anomaly.mean2true(M_rad, self.e)

    def getRpqw(self, t_dt=None):
        """Returns the 3-component position vector of the object at the given
           datetime, as evaluted in the PQW (co-planar) frame.
        """
        tht_rad = self.getTrue(t_dt)
        d = 1 + self.e * cos(tht_rad)
        p_m = self.a_m * (1 - self.e**2) * cos(tht_rad) / d
        q_m = self.a_m * (1 - self.e**2) * sin(tht_rad) / d
        return numpy.array([p_m, q_m, 0])

    def getQpqw2eci(self):
        """Returns the frame transformation matrix from the PQW (co-planar)
           frame to the earth-centered inertial (ECI) frame, w.r.t. J2000.
        """
        w = rot.Z(self.w_rad)
        i = rot.X(self.i_rad)
        O = rot.Z(self.O_rad)
        return (w.dot(i).dot(O)).transpose()

    def getReci(self, t_dt=None):
        """Returns the position of the object at the given point in time, as
           evaluated within the earth-centered inertial (ECI) frame, in meters.
        """
        rPqw = self.getRpqw(t_dt)
        Qpqw2eci = self.getQpqw2eci()
        return Qpqw2eci.dot(rPqw)

    def getRlla(self, t_dt=None):
        """Computes and returns the position at the given datetime, in latitude,
           longitude, and altitude (radians, radians, and meters, respectively).
        """
        if t_dt is None:
            t_dt = self.tEpoch_dt
        rEci_m = self.getReci(t_dt)
        rEcf_m = earth.getQeci2ecf(t_dt).dot(rEci_m)
        rLla_radm = rot.xyz2sph(rEcf_m)
        return numpy.array([rLla_radm[1], rLla_radm[0], rLla_radm[2] - earth.eqRad_m])

    def getAngMom(self):
        """Returns the scalar angular momentum of the orbit, in m/s^2.
        """
        return (earth.mu_m3ps2 * self.a_m * (1 - self.e**2))**0.5

    def getShape(self):
        """Returns a two-element tuple containing the altitude of the object at
           perigee and apogee, in meters above spherical sea level.
        """
        hPer_m = self.a_m * (1 - self.e) - earth.eqRad_m
        hApo_m = self.a_m * (1 + self.e) - earth.eqRad_m
        return (hPer_m, hApo_m)

    def getShapeVel(self):
        """Returns a two-element tuple containing the scalar velocity of the
           object at perigee and apogee, in meters per second.
        """
        rPer_m = self.a_m * (1 - self.e)
        rApo_m = self.a_m * (1 + self.e)
        h_m2ps = self.getAngMom()
        return h_m2ps / rPer_m, h_m2ps / rApo_m

    def getTaaRad(self):
        """Returns the true-anomaly averaged radius (geometric mean of radius at
           perigee and apogee), in meters.
        """
        rPer_m = self.a_m * (1 - self.e)
        rApo_m = self.a_m * (1 + self.e)
        return (rPer_m * rApo_m)**0.5

    def setShape(self, hPer_m, hApo_m):
        """Sets the a_m (semi-major axis) and e (eccentricity) values of an
           orbit based on the given altitude (meters above spherical sea level)
           at perigee and apogee.
        """
        rPer_m = hPer_m + earth.eqRad_m
        rApo_m = hApo_m + earth.eqRad_m
        self.a_m = 0.5 * (rPer_m + rApo_m)
        self.e = (rApo_m - rPer_m) / (rApo_m + rPer_m)

    def propagate(self, tEpoch_dt=None, T_s=None, nSamples=1000):
        """Computes inertial position over the course of one orbit, beginning
           with the given datetime (or, if not provided, the element epoch).
           This defaults to 1,000 samples within that time range.
        """
        if tEpoch_dt is None:
            tEpoch_dt = self.tEpoch_dt
        if T_s is None:
            T_s = self.getPeriod()
        ti_s = numpy.linspace(0, T_s, nSamples)
        rEci_m = numpy.zeros((0,3))
        for t_s in ti_s:
            r = self.getReci(tEpoch_dt + datetime.timedelta(t_s/86400))
            rEci_m = numpy.append(rEci_m, r.reshape(1,-1), axis=0)
        return rEci_m

    def track(self, tEpoch_dt=None, T_s=None, nSamples=1000):
        """Computes lat/lon/alt position over the course of one orbit, beginning
           with the given datetime (or, if not provided, the element epoch).
           This defaults to 1,000 samples within that time range.
        """
        if tEpoch_dt is None:
            tEpoch_dt = self.tEpoch_dt
        if T_s is None:
            T_s = self.getPeriod()
        ti_s = numpy.linspace(0, T_s, nSamples)
        rLla_radm = numpy.zeros((0,3))
        for t_s in ti_s:
            r = self.getRlla(tEpoch_dt + datetime.timedelta(t_s/86400))
            rLla_radm = numpy.append(rLla_radm, r.reshape(1,-1), axis=0)
        return rLla_radm

    def getApogee(self):
        """Returns the 3-component position vector of the object at apogee, in
           meters and evaluated within the earth-centered inertial (ECI) frame.
        """
        ra_m = self.a_m * (1 + self.e)
        return self.getQpqw2eci().dot(numpy.array([-ra_m,0,0]))

    def getPerigee(self):
        """Returns the 3-component position vector of the object at perigee, in
           meters and evaluated within the earth-centered inertial (ECI) frame.
        """
        rp_m = self.a_m * (1 - self.e)
        return self.getQpqw2eci().dot(numpy.array([rp_m,0,0]))

    def getAscNode(self):
        """Returns the 3-component position vector of the object at the
           ascending node, in meters and evaluated within the earth-centered
           inertial (ECI) frame.
        """
        tht_rad = 2 * pi - anomaly.mean2true(self.M_rad, self.e) - self.w_rad
        d = 1 + self.e * cos(tht_rad)
        p_m = self.a_m * (1 - self.e**2) * cos(tht_rad) / d
        q_m = self.a_m * (1 - self.e**2) * sin(tht_rad) / d
        rPqw_m = numpy.array([p_m, q_m, 0])
        return self.getQpqw2eci().dot(rPqw_m)

    def getDescNode(self):
        """Returns the 3-component position vector of the object at the
           descending node, in meters and evaluated within the earth-centered
           inertial (ECI) frame.
        """
        tht_rad = pi - anomaly.mean2true(self.M_rad, self.e) - self.w_rad
        d = 1 + self.e * cos(tht_rad)
        p_m = self.a_m * (1 - self.e**2) * cos(tht_rad) / d
        q_m = self.a_m * (1 - self.e**2) * sin(tht_rad) / d
        rPqw_m = numpy.array([p_m, q_m, 0])
        return self.getQpqw2eci().dot(rPqw_m)

    @classmethod
    def fromRV(cls, rEci_m, vEci_mps):
        """Constructs an Orbit object from the given position (meters) and
           velocity (meters-per-second) state vectors, as evaluated in the
           earth-centered inertial (ECI) frame.
        """
        r_m = rEci_m.dot(rEci_m)**0.5
        v_mps = vEci_mps.dot(vEci_mps)**0.5
        vr_mps = rEci_m.dot(vEci_mps) / r_m
        hEci_m2ps = numpy.cross(rEci_m, vEci_mps)
        h_m2ps = hEci_m2ps.dot(hEci_m2ps)**0.5
        i_rad = acos(hEci_m2ps[2] / h_m2ps)
        Neci = numpy.cross(numpy.array([0,0,1]), hEci_m2ps)
        N = Neci.dot(Neci)**0.5
        O_rad = acos(Neci[0] / N)
        if Neci[1] < 0:
            O_rad = 2 * pi - O_rad
        eEci = (numpy.cross(vEci_mps, hEci_m2ps) - earth.mu_m3ps2 * rEci_m / r_m) / earth.mu_m3ps2
        e = eEci.dot(eEci)**0.5
        w_rad = acos(Neci.dot(eEci) / N / e)
        if eEci[2] < 0:
            w_rad = 2 * pi - w_rad
        tht_rad = acos(eEci.dot(rEci_m) / e / r_m)
        if vr_mps < 0:
            tht_rad = 2 * pi - tht_rad
        M_rad = anomaly.true2mean(tht_rad, e)
        a_m = h_m2ps**2 / (earth.mu_m3ps2 * (1 - e**2))
        return cls(a_m=a_m, e=e, i_rad=i_rad, O_rad=O_rad, w_rad=w_rad, M_rad=M_rad)

    @classmethod
    def fromHTht(cls, h1_m, tht1_rad, h2_m, tht2_rad):
        """Constructs an Orbit object based on the given altitude (meters above
           spherical sea level) and true anomaly values (in radians).
        """
        r1_m = h1_m + earth.eqRad_m
        r2_m = h2_m + earth.eqRad_m
        e = (r1_m - r2_m) / (r2_m * cos(tht2_rad) - r1_m * cos(tht1_rad))
        h_m2ps = (r1_m * earth.mu_m3ps2 * (1 + e * cos(tht1_rad)))**0.5
        a_m = h_m2ps**2 / (earth.mu_m3ps2 * (1 - e**2))
        return cls(a_m=a_m, e=e)

    @classmethod
    def fromTle(cls, line1, line2):
        """Constructs an Orbit object from the given two strings, as formatted
           by the TLE (two-line element) specification (one string per line).
        """
        ey = line1[18:20]
        ed = line1[20:32]
        inc = line2[8:16]
        raan = line2[17:25]
        ecc = line2[26:33]
        aop = line2[34:42]
        ma = line2[43:51]
        mm = line2[52:63]
        a_m = (earth.mu_m3ps2 * (86400 / (2 * pi * float(mm)))**2)**(1/3)
        e = float('.' + ecc)
        i_rad = float(inc) * pi / 180
        O_rad = float(raan) * pi / 180
        w_rad = float(aop) * pi / 180
        M_rad = float(ma) * pi / 180
        tEpoch_y = 2000 + int(ey) if int(ey) < 50 else 1900 + int(ey)
        tEpoch_d = float(ed) - 1
        tEpoch_dt = datetime.datetime(tEpoch_y, 1, 1, 0, 0, 0) + datetime.timedelta(tEpoch_d)
        return cls(a_m=a_m, e=e, i_rad=i_rad, O_rad=O_rad, w_rad=w_rad, M_rad=M_rad, tEpoch_dt=tEpoch_dt)

class MeanJ2(Orbit):
    """Implements propagation to evolve elements with mean J2 perturbations
    """

    def getRaanRate(self):
        """Computes and returns the rate at which the right-ascension of the
           ascending node precesses, in radians per second, as a result of the
           non-spherical Earth's J2 harmonic.
        """
        return -1.5 * earth.mu_m3ps2**0.5 * earth.j2 * earth.eqRad_m**2 * cos(self.i_rad) / ((1 - self.e**2)**2 * self.a_m**3.5)

    def getAopRate(self):
        """Computes and returns the rate at which the argument of perigee
           processes, in radians per second, as a result of the non-spherical
           Earth's J2 harmonic.
        """
        return -1.5 * earth.mu_m3ps2**0.5 * earth.j2 * earth.eqRad_m**2 * (2.5 * sin(self.i_rad)**2 - 2) / ((1 - self.e**2)**2 * self.a_m**3.5)

    def getRaan(self, t_dt=None):
        """Computes the RAAN value of the object (in radians) at the given point
           in time, as propagated by the orbit-averaged mean precession computed
           in the *getRaanRate* method.
        """
        if t_dt is None:
            return self.O_rad
        dt_s = (t_dt - self.tEpoch_dt).total_seconds()
        dRaan_radps = self.getRaanRate()
        return (self.O_rad + dRaan_radps * dt_s) % (2 * pi)

    def getAop(self, t_dt=None):
        """Computes the AoP value of the object (in radians) at the given point
           in time, as propagated by the orbit-averaged mean precession computed
           in the *getAopRate* method.
        """
        if t_dt is None:
            return self.w_rad
        dt_s = (t_dt - self.tEpoch_dt).total_seconds()
        dAop_radps = self.getAopRate()
        return (self.w_rad + dAop_radps * dt_s) % (2 * pi)

    def getQpqw2eci(self, t_dt=None):
        """Returns a time-varying tranformation matrix that converts vectors
           from the PQW (co-orbital) frame to the earth-centered inertial (ECI)
           frame (w.r.t. the J2000 epochal orientation). This includes the RAAN
           precession and AoP procession rates induced by the J2 harmonic.
        """
        w = rot.Z(self.getAop(t_dt))
        i = rot.X(self.i_rad)
        O = rot.Z(self.getRaan(t_dt))
        return (w.dot(i).dot(O)).transpose()

    def getReci(self, t_dt=None):
        """Computes and returns the position of the object, in meters, as
           evaluted in the earth-centered inertial (ECI) frame. This includes
           the RAAN precession and ApP procession rates induced by J2 harmonic.
        """
        rPqw = self.getRpqw(t_dt)
        Qpqw2eci = self.getQpqw2eci(t_dt)
        return Qpqw2eci.dot(rPqw)

    @classmethod
    def fromSunSync(cls, T_s):
        """Returns a new MeanJ2 orbit object scaled to a specific inclination
           and altitude to achieve the given period, but with fixed RAAN
           (inclined such that the orbital plane orientation w.r.t. the sun
           remains constant).
        """
        a_m = (T_s * earth.mu_m3ps2**0.5 / (2 * pi))**(2/3)
        dRaan_radps = 2 * pi / earth.tSidYear_s
        d = -1.5 * earth.mu_m3ps2**0.5 * earth.j2 * earth.eqRad_m**2 / a_m**3.5
        i_rad = acos(dRaan_radps / d)
        return cls(a_m=a_m, i_rad=i_rad)

    @classmethod
    def fromConstAop(cls, T_s):
        """Determines an eccentric sun-synch orbit from the given period
        """
        a_m = (T_s * earth.mu_m3ps2**0.5 / (2 * pi))**(2/3)
        i_rad = pi - asin(0.8**0.5)
        dRaan_radps = 2 * pi / earth.tSidYear_s
        n = -3 * cos(i_rad) * earth.mu_m3ps2**0.5 * earth.j2 * earth.eqRad_m**2
        d = 2 * dRaan_radps * a_m**3.5
        e = (1 - (n / d)**0.5)**0.5
        return cls(a_m=a_m, e=e, i_rad=i_rad)

    @classmethod
    def fromMolniya(cls, lon_rad):
        """Returns a Molniya-style orbit designed to peak at the given longitude
           (in radians). Inclined to match RAAN recession to solar orientation.
        """
        i_rad = 63.4 * pi/180
        w_rad = 270 * pi/180
        T_s = 0.5 * earth.tSidDay_s
        a_m = ((T_s / (2 * pi))**2 * earth.mu_m3ps2)**(1/3)
        o = cls(a_m=a_m, e=0.74105, i_rad=i_rad, w_rad=w_rad)
        o.O_rad = (earth.getGmst(o.tEpoch_dt) + lon_rad) % (2 * pi)
        return o

    @classmethod
    def fromTundra(cls, lon_rad):
        """According to some definitions, tundra orbits do not necessarily match
           inclination to eliminate RAAN recession. QZSS, for example, targets
           apogee dwell at a specific latitude. While technically not requiring
           a J2 model, it is implemented here to support cases where the
           inclination (at 63.4 degrees) is choosen to ensure a fixed track.
        """
        i_rad = 63.4 * pi/180
        o = cls(e=0.25, i_rad=i_rad, w_rad=1.5*pi)
        gmst0_rad = earth.getGmst(o.tEpoch_dt)
        o.O_rad = (gmst0_rad + lon_rad - acos(cos(o.i_rad) * cos(o.w_rad)) + pi) % (2 * pi)
        return o

max_stars_repo_name: Tythos/oyb

max_issues_repo_name: Tythos/oyb

max_forks_repo_name: Tythos/oyb


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May  6 21:34:24 2020
@author: Francis Chen
"""

#---------------------DEFINE PACKAGE------------------------------------------
import numpy as np
import h5py
import matplotlib.pyplot as plt
import testCases
from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward
import lr_utils
np.random.seed(1)

#-------------------Programming Area------------------------------------------
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = lr_utils.load_dataset()
train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T
test_x_flatten  = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T

train_x = train_x_flatten / 255
train_y = train_set_y
test_x  = test_x_flatten / 255
test_y  = test_set_y

layers_dims = [12288,30,7,5,1]    # five layer model

# Through the dimension we see the weight and bias
def initialize_parameters_deep(layers_dims):
    np.random.seed(3)
    parameters = {}       # dictionary
    L=len(layers_dims)
    for l in range(1,L):  # For Each layer. 1-5 in this case
        parameters["W"+str(l)] = np.random.randn(layers_dims[l],layers_dims[l-1])/np.sqrt(layers_dims[l-1])  # All the column stroge the input feature and all the rows representing the number of nodes in next layer
        parameters["b"+str(l)] = np.zeros((layers_dims[l],1))
        assert(parameters["W"+str(l)].shape == (layers_dims[l],layers_dims[l-1]))
        assert(parameters["b"+str(l)].shape == (layers_dims[l],1))
    return parameters

# Through the input training data and weight and bias we finish forward prob.
def L_model_forward(X,parameters):
    caches = []
    A=X                      # X is acuallly the training data
    L=len(parameters) //2    # fix
    for l in range(1,L):
        A_prev = A
        A, cache = linear_activation_forward(A_prev, parameters['W'+str(l)],\
                                             parameters['b'+str(l)],"relu")
        caches.append(cache)
    AL , cache = linear_activation_forward(A,parameters['W'+str(L)],parameters['b'+str(L)],\
        "sigmoid")
    caches.append(cache)
    assert(AL.shape == (1,X.shape[1]))
    return AL, caches

# Calculating the cost
def compute_cost(AL,Y):
    m=Y.shape[1]
    cost = -np.sum(np.multiply(np.log(AL),Y)+np.multiply(np.log(1-AL),1-Y))/m
    cost = np.squeeze(cost)    # list,tuple --> array
    assert(cost.shape == ())
    return cost

# Through the cost we derive the grads
def L_model_backward(AL,Y,caches):
    grads = {}
    L = len(caches)
    m = AL.shape[1]
    Y = Y.reshape(AL.shape)
    dAL = -(np.divide(Y,AL) - np.divide(1-Y,1-AL))
    current_cache = caches[L-1]
    grads["dA"+str(L)],grads["dW"+str(L)],grads["db"+str(L)] = linear_activation_backward(dAL,current_cache,"sigmoid")
    for l in reversed(range(L-1)):
        current_cache = caches[l]
        dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA"+str(l+2)],current_cache,"relu")
        grads["dA"+str(l+1)] = dA_prev_temp
        grads["dW"+str(l+1)] = dW_temp
        grads["db"+str(l+1)] = db_temp
    return grads

# Through the parameters, grads and the hyper-parameter learning_rate, we finish the update
def update_parameters(parameters,grads,learning_rate):
    L=len(parameters) //2
    for l in range(L):
        parameters["W"+str(l+1)] = parameters["W"+str(l+1)] - learning_rate * grads["dW"+str(l+1)]
        parameters["b"+str(l+1)] = parameters["b"+str(l+1)] - learning_rate * grads["db"+str(l+1)]

    return parameters

#--------------------------------Finish One circut-----------------------------

def initialize_parameters(n_x,n_h,n_y):
    w1 = np.random.randn(n_h,n_x)*0.01  # Each Hidden nodes is coressponding to multiple input features
    b1 = np.zeros((n_h,1))              # The number of hidden layer is equal to the number of b needed
    w2 = np.random.randn(n_y,n_h)*0.01  # Each output args has n_h hidden layer connect to it
    b2 = np.zeros((n_y,1))              # Intialize b to be 0.
    assert(w1.shape == (n_h,n_x))       # If the input Args are wrong, the use assert we could identify the wronging problems
    assert(b1.shape == (n_h,1))
    assert(w2.shape == (n_y,n_h))
    assert(b2.shape == (n_y,1))
    parameters={"w1": w1,
                "b1": b1,
                "w2": w2,
                "b2": b2
        }
    return parameters

def linear_activation_forward(A_prev,W,b,activation):
    if activation == "sigmoid":
        Z,linear_cache = linear_forward(A_prev,W,b)
        A,activation_cache = sigmoid(Z)
    elif activation == "relu":
        Z,linear_cache = linear_forward(A_prev,W,b)
        A, activation_cache = relu(Z)
    assert(A.shape == (W.shape[0],A_prev.shape[1]))
    cache = (linear_cache, activation_cache)
    return A, cache

def linear_forward(A,W,b):
    Z=np.dot(W,A)+b
    assert(Z.shape == (W.shape[0],A.shape[1]))
    cache=(A,W,b)
    return Z,cache

def linear_backward(dZ,cache):
    A_prev, W, b=cache
    m  = A_prev.shape[1]
    dW = np.dot(dZ, A_prev.T) /m
    db = np.sum(dZ,axis=1, keepdims=True) / m
    dA_prev = np.dot(W.T,dZ)
    assert(dA_prev.shape == A_prev.shape)
    assert(dW.shape == W.shape)
    assert(db.shape == b.shape)
    return dA_prev, dW, db

def linear_activation_backward(dA,cache, activation = "relu"):
    linear_cache, activation_cache = cache
    if activation == "relu":
        dZ = relu_backward(dA,activation_cache)
        dA_prev, dW, db = linear_backward(dZ,linear_cache)
    elif activation == "sigmoid":
        dZ = sigmoid_backward(dA,activation_cache)
        dA_prev,dW,db = linear_backward(dZ,linear_cache)
    return dA_prev, dW, db

def Main(X,Y,layer_dims,learning_rate=0.0075,num_iterations=3000, print_cost=False, isPlot = True):
    np.random.seed(1)
    costs = []
    parameters = initialize_parameters_deep(layers_dims)
    for i in range(0,num_iterations):
        AL, caches = L_model_forward(X,parameters)
        cost  = compute_cost(AL, Y)
        grads = L_model_backward(AL,Y,caches)
        parameters = update_parameters(parameters,grads,learning_rate)
        if i % 100 == 0:
            costs.append(cost)
            if print_cost:
                print("The",i,"iteration cost is ", np.squeeze(cost))
    if isPlot:
            plt.plot(np.squeeze(costs))
            plt.ylabel('cost')
            plt.xlabel('iterations(per tens)')
            plt.title("Learning rate = " + str(learning_rate))
            plt.show()
    return parameters

parameters  = Main(train_x,train_y,layers_dims,learning_rate=0.0075,num_iterations=2500,print_cost=True,isPlot=True)
# 被程序直接调用的需要摆在最后面（？），其他程序编译关系随意（？）


text:
""" Transient two-phase (oil-water) flow """

from time import time

import numpy as np
import functools

import ressim
import utils

import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['image.cmap'] = 'jet'
import matplotlib.pyplot as plt

np.random.seed(42)  # for reproducibility

grid = ressim.Grid(nx=64, ny=64, lx=1.0, ly=1.0)  # unit square, 64x64 grid
k = np.exp(np.load('perm.npy').reshape(grid.shape))  # load log-permeability, convert to absolute with exp()
q = np.zeros(grid.shape); q[0,0]=1; q[-1,-1]=-1  # source term: corner-to-corner flow (a.k.a. quarter-five spot)

mu_w, mu_o = 1.0, 10.  # viscosities
s_wir, s_oir = 0.2, 0.2  # irreducible saturations

phi = np.ones(grid.shape)*0.2  # uniform porosity
s0 = np.ones(grid.shape) * s_wir  # initial water saturation equals s_wir
dt = 1e-3  # timestep

mobi_fn = functools.partial(utils.quadratic_mobility, mu_w=mu_w, mu_o=mu_o, s_wir=s_wir, s_oir=s_oir)  # quadratic mobility model
lamb_fn = functools.partial(utils.lamb_fn, mobi_fn=mobi_fn)  # total mobility function
f_fn = functools.partial(utils.f_fn, mobi_fn=mobi_fn)  # water fractional flow function

# (Optional) derivative of water fractional flow
# This is to compute the jacobian of the residual to accelerate the
# saturation solver. If not provided, the jacobian is approximated in the
# solver.
df_fn = functools.partial(utils.df_fn, mobi_fn=mobi_fn)

# instantiate solvers
solverP = ressim.PressureEquation(grid, q=q, k=k, lamb_fn=lamb_fn)
solverS = ressim.SaturationEquation(grid, q=q, phi=phi, s=s0, f_fn=f_fn, df_fn=df_fn)

# solve for 25 timesteps
nstep = 25
s_list = []
for i in range(nstep):
    before = time()

    # solve pressure
    solverP.s = solverS.s
    solverP.step()

    # solve saturation
    solverS.v = solverP.v
    solverS.step(dt)

    after = time()
    print '[{}/{}]: this loop took {} secs'.format(i+1, nstep, after - before)

    s_list.append(solverS.s)

# visualize
fig, axs = plt.subplots(5,5, figsize=(8,8))
fig.subplots_adjust(wspace=.1, hspace=.1, left=0, right=1, bottom=0, top=1)
for ax, s in zip(axs.ravel(), s_list):
    ax.imshow(s)
    ax.axis('off')
fig.savefig('saturations.png', bbox_inches=0, pad_inches=0)

max_stars_repo_name: chanshing/ressim

max_issues_repo_name: chanshing/ressim

max_forks_repo_name: chanshing/ressim


text:
import re
import matplotlib.pyplot as plt
import sys
import numpy as np
from matplotlib.ticker import FuncFormatter
import math
from collections import defaultdict
from matplotlib.patches import Patch
from matplotlib.ticker import ScalarFormatter
import brewer2mpl

bmap1 = brewer2mpl.get_map('Set1', 'Qualitative', 7)
bmap2 = brewer2mpl.get_map('Dark2', 'Qualitative', 7)
hash_colors = bmap1.mpl_colors
mix_colors = bmap2.mpl_colors

dory_1_color = hash_colors[2]
dory_2_color = hash_colors[4]
dory_4_color = hash_colors[1]
oram_color =  hash_colors[0]

plt.rcParams.update({'font.size':22})

dory_1_y = []
with open("out/dory_throughput_1_5_5.dat", 'r') as f:
    for i, line in enumerate(f):
        dory_1_y.append(float(line))

# N = 10000, n = 100
print(dory_1_y)

dory_2_y = []
with open("out/dory_throughput_2_5_5.dat", 'r') as f:
    for i, line in enumerate(f):
        dory_2_y.append(float(line))

# N = 10000, n = 100
print(dory_2_y)

dory_4_y = []
with open("out/dory_throughput_4_5_5.dat", 'r') as f:
    for i, line in enumerate(f):
        dory_4_y.append(float(line))

oram_y = []
with open("ref/oram_throughput_5_5.dat", 'r') as f:
    for i, line in enumerate(f):
        oram_y.append(float(line))

# N = 10000, n = 100

x = [2**i for i in range(10,21)]
oram_x = [2**i for i in range(10, len(oram_y) + 10)]

fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(111)
ax.loglog(x, dory_1_y, label=r"DORY ($p=1$)", basex=2, basey=10, color=dory_1_color, linewidth=1)
ax.loglog(x, dory_2_y, label=r"DORY ($p=2$)", basex=2, basey=10, color=dory_2_color, linewidth=1)
ax.loglog(x, dory_4_y, label=r"DORY ($p=4$)", basex=2, basey=10, color=dory_4_color, linewidth=1)
ax.loglog(oram_x, oram_y, label=r"PathORAM baseline", basex=2, basey=10, color=oram_color, linewidth=1, linestyle="dashed")
ax.set_xlabel("# Documents")
ax.set_ylabel("Operations/sec")
ax.set_xticks([1024, 32768, 1048576])
ax.set_yticks([100, 1, 0.01, 0.0001])
ax.set_title("50% U, 50% S")

plt.legend()
plt.tight_layout()
plt.savefig("out/fig10b.png")
plt.show()


text:
#need to have gfortran installed, then call 'make' to compile .so file, then this will successfully import
from h2o_pot import calc_hoh_pot
import numpy as np

def water_pot(cds):
    return calc_hoh_pot(cds, len(cds))

if __name__ == '__main__':
    x = np.random.random((100, 3, 3))
    v = water_pot(x)
    print(v)

max_stars_repo_name: McCoyGroup/pyvibdmc

max_issues_repo_name: McCoyGroup/pyvibdmc

max_forks_repo_name: McCoyGroup/pyvibdmc


text:
import numpy as np

from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.util.hex import axial_to_cartesian

output_file("hex_coords.html")

q = np.array([0,  0, 0, -1, -1,  1, 1])
r = np.array([0, -1, 1,  0,  1, -1, 0])

p = figure(plot_width=400, plot_height=400, toolbar_location=None)
p.grid.visible = False

p.hex_tile(q, r, size=1, fill_color=["firebrick"]*3 + ["navy"]*4,
           line_color="white", alpha=0.5)

x, y = axial_to_cartesian(q, r, 1, "pointytop")

p.text(x, y, text=["(%d, %d)" % (q,r) for (q, r) in zip(q, r)],
       text_baseline="middle", text_align="center")

show(p)


text:
import cv2
import numpy as np
from math import *

# 设定两个转换矩阵
RGB2IHS = np.array([(1/sqrt(3), 1/sqrt(3), 1/sqrt(3)),
                    (-2/sqrt(6), 1/sqrt(6), 1/sqrt(6)),   # RGB->IHS逆变换矩阵
                    (0, -1/sqrt(2), 1/sqrt(2))])
IHS2RGB = np.array([(1/sqrt(3), -2/sqrt(6), 0),
                    (1/sqrt(3), 1/sqrt(6), -1/sqrt(2)),   # IHS->RGB逆变换矩阵
                    (1/sqrt(3), 1/sqrt(6), 1/sqrt(2))])

if __name__ == "__main__":
    # 两幅图
    low_rgb = cv2.imread("images/low.jpg")
    high_rgb = cv2.imread("images/high.jpg")

    rows, cols, color = high_rgb.shape
    b, g, r = cv2.split(low_rgb)
    low_rgb.astype(np.float64)  # 将unit8转换成float64数据类型
    high_rgb.astype(np.float64)

    img_fus = np.zeros((rows, cols, 3), dtype=np.uint8)  # 创建空图作为融合后的存储

    for i in range(rows):
        for j in range(cols):
            low_d = RGB2IHS.dot(low_rgb[i, j, :])
            high_d = RGB2IHS.dot(high_rgb[i, j, :])  # 正变换
            tmp = np.array([high_d[0], low_d[1], low_d[2]])  # 采用高分辨率图像的明度

            fus = IHS2RGB.dot(tmp)
            img_fus[i, j, 0] = max(min(fus[0], 255), 0)
            img_fus[i, j, 1] = max(min(fus[1], 255), 0)
            img_fus[i, j, 2] = max(min(fus[2], 255), 0)  # 逆变换

    cv2.imshow("low", low_rgb)
    cv2.imshow("high", high_rgb)
    cv2.imshow("fusion", img_fus)
    cv2.waitKey(0)
cv2.destroyAllWindows()

max_stars_repo_path: Image Fusion/HSI.py

max_issues_repo_path: Image Fusion/HSI.py

max_forks_repo_path: Image Fusion/HSI.py


text:
#!/usr/bin/env python3
import numpy as np

def integral(ifrom,ito,func,dx=1e-9):
    x=np.arange(ifrom,ito,dx)
    dy=func(x)*dx
    return np.sum(dy)

def f(x):
    return np.sin(x)

if __name__=="__main__":
    predict=integral(0,10,f)

max_stars_repo_name: TravorLZH/calculus

max_issues_repo_name: TravorLZH/calculus

max_forks_repo_name: TravorLZH/calculus